FilteredCRUDService2Impl.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.genesys.blocks.model.filters.EmptyModelFilter;
import org.gringlobal.api.v1.MultiOp;
import org.gringlobal.service.CRUDService2;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
/**
* The basic FilteredCRUDServiceImpl.
*
* @param <E> the model type
* @param <F> the model filter type
* @param <R> the repository type
*/
@Transactional(readOnly = true)
@Validated
public abstract class FilteredCRUDService2Impl<E extends EmptyModel, F extends EmptyModelFilter<F, E>, R extends JpaRepository<E, Long> & QuerydslPredicateExecutor<E>> extends
FilteredCRUDServiceImpl<E, F, R> implements CRUDService2<E> {
@Override
public final List<E> get(List<E> 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 E createFast(E source) {
return repository.save(source);
}
@Override
@Transactional
/* Override to use {@code createFast(...)} */
public MultiOp<E> createFast(List<E> inserts) {
var result = new MultiOp<E>();
result.success = new ArrayList<E>(inserts.size());
for (E one : inserts) {
result.success.add(this.createFast(one));
}
return result;
}
@Override
@Transactional
public E updateFast(E updated) {
entityManager.detach(updated); // Ensure that EM does not reuse incoming entity
E target = get(updated);
return updateFast(updated, target);
}
@Override
@Transactional
/* Override to use {@code updateFast(...)} */
public MultiOp<E> updateFast(List<E> updates) {
var result = new MultiOp<E>();
result.success = new ArrayList<E>(updates.size());
for (E one : updates) {
result.success.add(this.updateFast(one, get(one)));
}
return result;
}
}