Search in sources :

Example 1 with CriteriaWhereQuery

use of com.github.tfaga.lynx.beans.CriteriaWhereQuery in project lynx by TFaga.

the class JPAUtils method queryEntitiesCount.

public static <T> Long queryEntitiesCount(EntityManager em, Class<T> entity, QueryParameters q, CriteriaFilter<T> customFilter) {
    if (em == null || entity == null)
        throw new IllegalArgumentException("The entity manager and the entity cannot be null.");
    if (q == null)
        throw new IllegalArgumentException("Query parameters can't be null. " + "If you don't have any parameters either pass a empty object or " + "use the queryEntitiesCount(EntityManager, Class<T>) method.");
    log.finest("Querying entity count: '" + entity.getSimpleName() + "' with parameters: " + q);
    Boolean requiresDistinct = false;
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<T> r = cq.from(entity);
    Predicate wherePredicate = null;
    if (!q.getFilters().isEmpty()) {
        CriteriaWhereQuery criteriaWhereQuery = createWhereQueryInternal(cb, r, q);
        requiresDistinct = criteriaWhereQuery.containsToMany();
        wherePredicate = criteriaWhereQuery.getPredicate();
    }
    if (customFilter != null) {
        wherePredicate = customFilter.createPredicate(wherePredicate == null ? cb.conjunction() : wherePredicate, cb, r);
    }
    if (wherePredicate != null) {
        cq.where(wherePredicate);
    }
    cq.select(cb.count(r)).distinct(requiresDistinct);
    return em.createQuery(cq).getSingleResult();
}
Also used : CriteriaWhereQuery(com.github.tfaga.lynx.beans.CriteriaWhereQuery)

Example 2 with CriteriaWhereQuery

use of com.github.tfaga.lynx.beans.CriteriaWhereQuery in project lynx by TFaga.

the class JPAUtils method queryEntities.

@SuppressWarnings("unchecked")
public static <T> List<T> queryEntities(EntityManager em, Class<T> entity, QueryParameters q, CriteriaFilter<T> customFilter) {
    if (em == null || entity == null)
        throw new IllegalArgumentException("The entity manager and the entity cannot be null.");
    if (q == null)
        throw new IllegalArgumentException("Query parameters can't be null. " + "If you don't have any parameters either pass a empty object or " + "use the queryEntities(EntityManager, Class<T>) method.");
    log.finest("Querying entity: '" + entity.getSimpleName() + "' with parameters: " + q);
    Boolean requiresDistinct = false;
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<?> cq;
    if (q.getFields().isEmpty()) {
        cq = cb.createQuery(entity);
    } else {
        cq = cb.createTupleQuery();
    }
    Root<T> r = cq.from(entity);
    Predicate wherePredicate = null;
    if (!q.getFilters().isEmpty()) {
        CriteriaWhereQuery criteriaWhereQuery = createWhereQueryInternal(cb, r, q);
        requiresDistinct = criteriaWhereQuery.containsToMany();
        wherePredicate = criteriaWhereQuery.getPredicate();
    }
    if (customFilter != null) {
        wherePredicate = customFilter.createPredicate(wherePredicate == null ? cb.conjunction() : wherePredicate, cb, r);
    }
    if (wherePredicate != null) {
        cq.where(wherePredicate);
    }
    if (!q.getOrder().isEmpty()) {
        List<Order> orders = createOrderQuery(cb, r, q, getEntityIdField(em, entity));
        cq.orderBy(orders);
    }
    if (q.getFields().isEmpty()) {
        cq.select((Selection) r).distinct(requiresDistinct);
    } else {
        cq.multiselect(createFieldsSelect(r, q, getEntityIdField(em, entity))).distinct(requiresDistinct);
    }
    TypedQuery<?> tq = em.createQuery(cq);
    if (q.getLimit() != null && q.getLimit() > -1) {
        tq.setMaxResults(q.getLimit().intValue());
    }
    if (q.getOffset() != null && q.getOffset() > -1) {
        tq.setFirstResult(q.getOffset().intValue());
    }
    if (q.getFields().isEmpty()) {
        return (List<T>) tq.getResultList();
    } else {
        return createEntityFromTuple((List<Tuple>) tq.getResultList(), entity);
    }
}
Also used : CriteriaWhereQuery(com.github.tfaga.lynx.beans.CriteriaWhereQuery) ArrayList(java.util.ArrayList) List(java.util.List) Tuple(javax.persistence.Tuple)

Example 3 with CriteriaWhereQuery

use of com.github.tfaga.lynx.beans.CriteriaWhereQuery in project lynx by TFaga.

the class JPAUtils method createWhereQueryInternal.

// Temporary methods to not break the public API
private static CriteriaWhereQuery createWhereQueryInternal(CriteriaBuilder cb, Root<?> r, QueryParameters q) {
    Predicate predicate = cb.conjunction();
    Boolean containsToMany = false;
    for (QueryFilter f : q.getFilters()) {
        Predicate np = null;
        try {
            CriteriaField criteriaField = getCriteriaField(f.getField(), r);
            if (criteriaField.containsToMany()) {
                containsToMany = true;
            }
            Path entityField = criteriaField.getPath();
            if (entityField.getModel() == null || !((Attribute) entityField.getModel()).getPersistentAttributeType().equals(Attribute.PersistentAttributeType.BASIC)) {
                continue;
            }
            @SuppressWarnings("unchecked") Path<String> stringField = (Path<String>) entityField;
            switch(f.getOperation()) {
                case EQ:
                    if (f.getValue() != null) {
                        np = cb.equal(entityField, getValueForPath(entityField, f.getValue()));
                    }
                    break;
                case EQIC:
                    if (isClassStringLike(entityField.getJavaType()) && f.getValue() != null) {
                        np = cb.equal(cb.lower(stringField), getValueForPath(entityField, f.getValue().toLowerCase()));
                    }
                    break;
                case NEQ:
                    if (f.getValue() != null) {
                        np = cb.notEqual(entityField, getValueForPath(entityField, f.getValue()));
                    }
                    break;
                case NEQIC:
                    if (isClassStringLike(entityField.getJavaType()) && f.getValue() != null) {
                        np = cb.notEqual(cb.lower(stringField), getValueForPath(entityField, f.getValue().toLowerCase()));
                    }
                    break;
                case LIKE:
                    if (entityField.getJavaType() == String.class && f.getValue() != null) {
                        np = cb.like(stringField, f.getValue());
                    }
                    break;
                case LIKEIC:
                    if (entityField.getJavaType() == String.class && f.getValue() != null) {
                        np = cb.like(cb.lower(stringField), f.getValue().toLowerCase());
                    }
                    break;
                case GT:
                    if (isClassComparable(entityField.getJavaType()) && f.getValue() != null) {
                        np = cb.greaterThan(entityField, (Comparable) getValueForPath(stringField, f.getValue()));
                    }
                    break;
                case GTE:
                    if (isClassComparable(entityField.getJavaType()) && f.getValue() != null) {
                        np = cb.greaterThanOrEqualTo(entityField, (Comparable) getValueForPath(stringField, f.getValue()));
                    }
                    break;
                case LT:
                    if (isClassComparable(entityField.getJavaType()) && f.getValue() != null) {
                        np = cb.lessThan(entityField, (Comparable) getValueForPath(stringField, f.getValue()));
                    }
                    break;
                case LTE:
                    if (isClassComparable(entityField.getJavaType()) && f.getValue() != null) {
                        np = cb.lessThanOrEqualTo(entityField, (Comparable) getValueForPath(stringField, f.getValue()));
                    }
                    break;
                case IN:
                    np = entityField.in(f.getValues().stream().filter(Objects::nonNull).map(s -> getValueForPath(entityField, s)).collect(Collectors.toList()));
                    break;
                case INIC:
                    if (isClassStringLike(entityField.getJavaType())) {
                        np = cb.lower(stringField).in(f.getValues().stream().filter(Objects::nonNull).map(String::toLowerCase).map(s -> getValueForPath(entityField, s)).collect(Collectors.toList()));
                    }
                    break;
                case NIN:
                    np = cb.not(entityField.in(f.getValues().stream().filter(Objects::nonNull).map(s -> getValueForPath(entityField, s)).collect(Collectors.toList())));
                    break;
                case NINIC:
                    if (isClassStringLike(entityField.getJavaType())) {
                        np = cb.not(cb.lower(stringField).in(f.getValues().stream().filter(Objects::nonNull).map(String::toLowerCase).map(s -> getValueForPath(entityField, s)).collect(Collectors.toList())));
                    }
                    break;
                case ISNULL:
                    np = cb.isNull(entityField);
                    break;
                case ISNOTNULL:
                    np = cb.isNotNull(entityField);
                    break;
            }
        } catch (IllegalArgumentException e) {
            throw new NoSuchEntityFieldException(e.getMessage(), f.getField(), r.getJavaType().getSimpleName());
        }
        if (np != null) {
            predicate = cb.and(predicate, np);
        }
    }
    return new CriteriaWhereQuery(predicate, containsToMany);
}
Also used : CriteriaFilter(com.github.tfaga.lynx.interfaces.CriteriaFilter) TypedQuery(javax.persistence.TypedQuery) InvalidEntityFieldException(com.github.tfaga.lynx.exceptions.InvalidEntityFieldException) ArrayList(java.util.ArrayList) ConversionException(com.github.tfaga.lynx.exceptions.ConversionException) NoSuchEntityFieldException(com.github.tfaga.lynx.exceptions.NoSuchEntityFieldException) EntityType(javax.persistence.metamodel.EntityType) QueryFilter(com.github.tfaga.lynx.beans.QueryFilter) CriteriaField(com.github.tfaga.lynx.beans.CriteriaField) javax.persistence.criteria(javax.persistence.criteria) Metamodel(javax.persistence.metamodel.Metamodel) QueryParameters(com.github.tfaga.lynx.beans.QueryParameters) Tuple(javax.persistence.Tuple) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) OrderDirection(com.github.tfaga.lynx.enums.OrderDirection) Set(java.util.Set) EntityManager(javax.persistence.EntityManager) Field(java.lang.reflect.Field) Logger(java.util.logging.Logger) CriteriaWhereQuery(com.github.tfaga.lynx.beans.CriteriaWhereQuery) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) Objects(java.util.Objects) List(java.util.List) InvalidFieldValueException(com.github.tfaga.lynx.exceptions.InvalidFieldValueException) ConversionHelper(com.github.tfaga.lynx.helper.ConversionHelper) TupleElement(javax.persistence.TupleElement) QueryFilter(com.github.tfaga.lynx.beans.QueryFilter) CriteriaWhereQuery(com.github.tfaga.lynx.beans.CriteriaWhereQuery) Objects(java.util.Objects) CriteriaField(com.github.tfaga.lynx.beans.CriteriaField) NoSuchEntityFieldException(com.github.tfaga.lynx.exceptions.NoSuchEntityFieldException)

Aggregations

CriteriaWhereQuery (com.github.tfaga.lynx.beans.CriteriaWhereQuery)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Tuple (javax.persistence.Tuple)2 CriteriaField (com.github.tfaga.lynx.beans.CriteriaField)1 QueryFilter (com.github.tfaga.lynx.beans.QueryFilter)1 QueryParameters (com.github.tfaga.lynx.beans.QueryParameters)1 OrderDirection (com.github.tfaga.lynx.enums.OrderDirection)1 ConversionException (com.github.tfaga.lynx.exceptions.ConversionException)1 InvalidEntityFieldException (com.github.tfaga.lynx.exceptions.InvalidEntityFieldException)1 InvalidFieldValueException (com.github.tfaga.lynx.exceptions.InvalidFieldValueException)1 NoSuchEntityFieldException (com.github.tfaga.lynx.exceptions.NoSuchEntityFieldException)1 ConversionHelper (com.github.tfaga.lynx.helper.ConversionHelper)1 CriteriaFilter (com.github.tfaga.lynx.interfaces.CriteriaFilter)1 Field (java.lang.reflect.Field)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Objects (java.util.Objects)1 Set (java.util.Set)1 Logger (java.util.logging.Logger)1 Collectors (java.util.stream.Collectors)1