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

com.hiczp.jpa.repository.select.Utils Maven / Gradle / Ivy

package com.hiczp.jpa.repository.select;

import org.springframework.data.jpa.domain.Specification;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.Arrays;
import java.util.List;

class Utils {
    static  Specification createSpecification(T entity) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            List> expressions = predicate.getExpressions();

            Arrays.stream(entity.getClass().getDeclaredFields())
                    .filter(field -> field.isAnnotationPresent(Column.class) || field.isAnnotationPresent(Id.class))
                    .forEach(field -> {
                        try {
                            field.setAccessible(true);
                            Object value = field.get(entity);
                            if (value == null || value.equals(0) || value.equals(false)) {
                                return;
                            }
                            expressions.add(criteriaBuilder.equal(root.get(field.getName()), value));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    });

            return predicate;
        };
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy