CRUDService2Impl.java

/*
 * Copyright 2024 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.server.service.impl;

import com.querydsl.jpa.impl.JPAQueryFactory;

import lombok.extern.slf4j.Slf4j;

import org.genesys.blocks.model.EmptyModel;
import org.genesys.server.api.v2.MultiOp;
import org.genesys.server.service.CRUDService2;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * The basic FilteredCRUDServiceImpl.
 *
 * @param <T> the model type
 * @param <R> the repository type
 */
@Transactional(readOnly = true)
@Slf4j
public abstract class CRUDService2Impl<T extends EmptyModel, R extends JpaRepository<T, Long>> extends CRUDServiceImpl<T, R> implements CRUDService2<T> {

	/** The repository. */
	@Autowired
	protected R repository;

	@Autowired
	protected JPAQueryFactory jpaQueryFactory;

	@PersistenceContext
	protected EntityManager entityManager;

	/**
	 * Gets list of entites by ID from the database, keeping the sort order of the original list
	 */
	@Override
	public List<T> get(List<T> list) {
		var idList = list.stream().map(EmptyModel::getId).filter(Objects::nonNull).collect(Collectors.toList());
		Comparator<T> sorter = (a, b) -> Integer.compare(idList.indexOf(a.getId()), idList.indexOf(b.getId())); // Keep order of items
		var r = repository.findAllById(idList);
		r.sort(sorter);
		return r;
	}

	@Override
	@Transactional
	public T createFast(T source) {
		return repository.save(source);
	}

	@Override
	@Transactional
	/* Override to use {@code createFast(...)} */
	public MultiOp<T> createFast(List<T> inserts) {
		var result = new MultiOp<T>();
		result.success = new LinkedList<T>();
		for (T one : inserts) {
			result.success.add(this.createFast(one));
		}
		return result;
	}

	@Override
	@Transactional
	/* Override to use {@code updateFast(...)} */
	public MultiOp<T> updateFast(List<T> updates) {
		var result = new MultiOp<T>();
		result.success = new LinkedList<T>();
		for (T one : updates) {
			result.success.add(this.updateFast(one, get(one)));
		}
		return result;
	}
}