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.LinkedList;
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.MultiOp;
import org.gringlobal.api.exception.InvalidApiUsageException;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.service.CRUDService2;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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 Page<E> list(F filter, Pageable page) throws SearchException {
return super.list(adjustFilter(filter), page);
}
/**
* Adjust filter lets us add additional constraints
* @param filter the original filter
* @return adjusted filter
*/
protected F adjustFilter(F filter) {
return filter;
}
@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) {
if (! source.isNew()) throw new InvalidApiUsageException("id must be null for a new record");
return repository.save(source);
}
@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);
}
}