All Downloads are FREE. Search and download functionalities are using the official Maven repository.

driven-adapter.jpa-repository.helper.adapter-operations.mustache Maven / Gradle / Ivy

Go to download

Gradle plugin to create a clean application in Java that already works, It follows our best practices!

There is a newer version: 3.20.10
Show newest version
package {{package}}.jpa.helper;

import org.reactivecommons.utils.ObjectMapper;
import org.springframework.data.domain.Example;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.function.Function;

import static java.util.stream.StreamSupport.stream;

public abstract class AdapterOperations & QueryByExampleExecutor> {
    protected R repository;
    private Class dataClass;
    protected ObjectMapper mapper;
    private Function toEntityFn;

    @SuppressWarnings("unchecked")
    protected AdapterOperations(R repository, ObjectMapper mapper, Function toEntityFn) {
        this.repository = repository;
        this.mapper = mapper;
        ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
        this.dataClass = (Class) genericSuperclass.getActualTypeArguments()[1];
        this.toEntityFn = toEntityFn;
    }

    protected D toData(E entity) {
        return mapper.map(entity, dataClass);
    }

    protected E toEntity(D data) {
        return data != null ? toEntityFn.apply(data) : null;
    }

    public E save(E entity) {
        D data = toData(entity);
        return toEntity(saveData(data));
    }

    protected List saveAllEntities(List entities) {
        List list = entities.stream().map(this::toData).toList();
        return toList(saveData(list));
    }

    public List toList(Iterable iterable) {
        return stream(iterable.spliterator(), false).map(this::toEntity).toList();
    }

    protected D saveData(D data) {
        return repository.save(data);
    }

    protected Iterable saveData(List data) {
        return repository.saveAll(data);
    }

    public E findById(I id) {
        return toEntity(repository.findById(id).orElse(null));
    }

    public List findByExample(E entity) {
        return toList(repository.findAll( Example.of(toData(entity))));
    }


    public List findAll(){
        return toList(repository.findAll());
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy