CRUDService2Impl.java

/*
 * Copyright 2023 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.gringlobal.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.genesys.blocks.model.EmptyModel;
import org.gringlobal.api.v1.MultiOp;
import org.gringlobal.service.CRUDService2;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

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

	@Override
	@Transactional(readOnly = true)
	public final List<T> get(List<T> list) {
		// result must maintain order of items in list
		var sourceIds = list.stream().map(EmptyModel::getId).filter(Objects::nonNull).collect(Collectors.toList());
		var res = repository.findAllById(sourceIds);
		res.sort((a, b) -> {
			return Integer.compare(sourceIds.indexOf(a.getId()), sourceIds.indexOf(b.getId()));
		});
		return res;
	}

	@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 ArrayList<T>(inserts.size());
		for (T one : inserts) {
			result.success.add(this.createFast(one));
		}
		return result;
	}

	@Override
	@Transactional
	public T updateFast(T updated) {
		entityManager.detach(updated); // Ensure that EM does not reuse incoming entity
		T target = get(updated);
		return updateFast(updated, target);
	}

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