Java Code Examples for org.springframework.data.jpa.domain.Specification#toPredicate()

The following examples show how to use org.springframework.data.jpa.domain.Specification#toPredicate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CodelessDaoProxy.java    From sca-best-practice with Apache License 2.0 6 votes vote down vote up
private <S, T> Root<T> applySpecificationToCriteria(Class<T> clazz, @Nullable Specification<T> spec,
                                                    CriteriaQuery<S> query) {

    Assert.notNull(clazz, "Domain class must not be null!");
    Assert.notNull(query, "CriteriaQuery must not be null!");

    Root<T> root = query.from(clazz);

    if (spec == null) {
        return root;
    }

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    Predicate predicate = spec.toPredicate(root, query, builder);

    if (predicate != null) {
        query.where(predicate);
    }

    return root;
}
 
Example 2
Source File: JpaSpecificationExecutorWithProjectionImpl.java    From specification-with-projection with MIT License 6 votes vote down vote up
private <S, U extends T> Root<U> applySpecificationToCriteria(@Nullable Specification<U> spec, Class<U> domainClass,
                                                              CriteriaQuery<S> query) {

    Assert.notNull(domainClass, "Domain class must not be null!");
    Assert.notNull(query, "CriteriaQuery must not be null!");

    Root<U> root = query.from(domainClass);

    if (spec == null) {
        return root;
    }

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    Predicate predicate = spec.toPredicate(root, query, builder);

    if (predicate != null) {
        query.where(predicate);
    }

    return root;
}
 
Example 3
Source File: GenericJpaRepositoryImpl.java    From genericdao with Artistic License 2.0 6 votes vote down vote up
protected <S> Root<T> applySpecificationToCriteria(Specification<T> spec, CriteriaQuery<S> query) {

		Assert.notNull(query);
		Root<T> root = query.from(getDomainClass());

		if (spec == null) {
			return root;
		}

		CriteriaBuilder builder = entityManager.getCriteriaBuilder();
		Predicate predicate = spec.toPredicate(root, query, builder);

		if (predicate != null) {
			query.where(predicate);
		}

		return root;
	}
 
Example 4
Source File: Conjunction.java    From specification-arg-resolver with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
   public void initializeFakes(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
   	if (!fakesInitialized) {
    	for (Specification<T> spec : innerSpecs) {
    		if (spec instanceof FakeSpecWrapper) {
        		((FakeSpecWrapper<T>) spec).initializeFakes(root, query, cb);
        	}
        	if (spec instanceof Fake) {
        		spec.toPredicate(root, query, cb);
        		continue;
        	}
    	}
   	}
   	fakesInitialized = true;
   }
 
Example 5
Source File: Conjunction.java    From specification-arg-resolver with Apache License 2.0 6 votes vote down vote up
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
	initializeFakes(root, query, cb);
    Specification<T> combinedSpecs = null;
    for (Specification<T> spec : innerSpecs) {
    	if (spec instanceof Fake) {
    		continue;
    	}
        if (combinedSpecs == null) {
            combinedSpecs = Specification.where(spec);
        } else {
            combinedSpecs = combinedSpecs.and(spec);
        }
    }
    return combinedSpecs == null ? null : combinedSpecs.toPredicate(root, query, cb);
}
 
Example 6
Source File: SimpleBaseRepository.java    From es with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the given {@link org.springframework.data.jpa.domain.Specification} to the given {@link javax.persistence.criteria.CriteriaQuery}.
 *
 * @param spec  can be {@literal null}.
 * @param query must not be {@literal null}.
 * @return
 */
private <S> Root<M> applySpecificationToCriteria(Specification<M> spec, CriteriaQuery<S> query) {

    Assert.notNull(query);
    Root<M> root = query.from(entityClass);

    if (spec == null) {
        return root;
    }

    CriteriaBuilder builder = em.getCriteriaBuilder();
    Predicate predicate = spec.toPredicate(root, query, builder);

    if (predicate != null) {
        query.where(predicate);
    }

    return root;
}
 
Example 7
Source File: CountSpecificationInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Number intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Number> context) {
    final Object parameterValue = context.getParameterValues()[0];
    if (parameterValue instanceof Specification) {
        Specification specification = (Specification) parameterValue;
        final EntityManager entityManager = jpaOperations.getCurrentEntityManager();
        final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        final CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
        final Root<?> root = query.from(getRequiredRootEntity(context));
        final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder);
        query.where(predicate);
        if (query.isDistinct()) {
            query.select(criteriaBuilder.countDistinct(root));
        } else {
            query.select(criteriaBuilder.count(root));
        }
        query.orderBy(Collections.emptyList());

        final TypedQuery<Long> typedQuery = entityManager.createQuery(query);
        final Long result = typedQuery.getSingleResult();
        final ReturnType<Number> rt = context.getReturnType();
        final Class<Number> returnType = rt.getType();
        if (returnType.isInstance(result)) {
            return result;
        } else {
            return ConversionService.SHARED.convertRequired(
                    result,
                    rt.asArgument()
            );
        }
    } else {
        throw new IllegalArgumentException("Argument must be an instance of: " + Specification.class);
    }
}
 
Example 8
Source File: FindOneSpecificationInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    final Object parameterValue = context.getParameterValues()[0];
    if (parameterValue instanceof Specification) {
        Specification specification = (Specification) parameterValue;
        final EntityManager entityManager = jpaOperations.getCurrentEntityManager();
        final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        final CriteriaQuery<Object> query = criteriaBuilder.createQuery((Class<Object>) getRequiredRootEntity(context));
        final Root<Object> root = query.from((Class<Object>) getRequiredRootEntity(context));
        final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder);
        query.where(predicate);
        query.select(root);

        final TypedQuery<?> typedQuery = entityManager.createQuery(query);
        try {
            final Object result = typedQuery.getSingleResult();
            final ReturnType<?> rt = context.getReturnType();
            final Class<?> returnType = rt.getType();
            if (returnType.isInstance(result)) {
                return result;
            } else {
                return ConversionService.SHARED.convertRequired(
                        result,
                        rt.asArgument()
                );
            }
        } catch (NoResultException e) {
            if (context.isNullable()) {
                return null;
            } else {
                throw new EmptyResultDataAccessException(1);
            }
        }
    } else {
        throw new IllegalArgumentException("Argument must be an instance of: " + Specification.class);
    }
}
 
Example 9
Source File: SpecificationImpl.java    From spring-repository-plus with Apache License 2.0 5 votes vote down vote up
@Override
public Predicate toPredicate(Root<Object> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<>();
    for(Specification specification: specifications){
        Predicate p = specification.toPredicate(root, cq, cb);
        if(p!=null)
            predicates.add(p);
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
 
Example 10
Source File: JpaSpecificationExecutorWithProjectionImpl.java    From specification-with-projection with MIT License 5 votes vote down vote up
protected TypedQuery<Tuple> getTupleQuery(@Nullable Specification spec, Sort sort, ReturnedType returnedType) {
    if (!returnedType.needsCustomConstruction()){
        return getQuery(spec,sort);
    }
    CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> query = builder.createQuery(Tuple.class);
    Root<T> root = this.applySpecificationToCriteria(spec, getDomainClass(), query);
    Predicate predicate = spec.toPredicate(root, query, builder);

    if (predicate != null) {
        query.where(predicate);
    }
    if (returnedType.needsCustomConstruction()) {
        List<Selection<?>> selections = new ArrayList<>();

        for (String property : returnedType.getInputProperties()) {
            PropertyPath path = PropertyPath.from(property, returnedType.getReturnedType());
            selections.add(toExpressionRecursively(root, path, true).alias(property));
        }

        query.multiselect(selections);
    } else {
        throw new IllegalArgumentException("only except projection");
    }
    if (sort.isSorted()) {
        query.orderBy(QueryUtils.toOrders(sort, root, builder));
    }

    return this.applyRepositoryMethodMetadata(this.entityManager.createQuery(query));
}
 
Example 11
Source File: AclJpaQuery.java    From strategy-spring-security-acl with Apache License 2.0 5 votes vote down vote up
private void installAclSpec(Specification<Object> aclJpaSpec) {
  // force rerender by resetting alias
  root.alias(null);

  // build acl predicate
  Predicate aclPredicate =
        aclJpaSpec.toPredicate(root, cachedCriteriaQuery, em.getCriteriaBuilder());

  // install acl predicate
  aclPredicateTargetSource.installAcl(aclPredicate);

  logger.debug("ACL Jpa Specification installed for method '{}' and query {}: {}", method,
        query, aclJpaSpec);
}
 
Example 12
Source File: GenericRepositoryImpl.java    From HA-DB with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private <S> S aggregate(CriteriaBuilder builder, CriteriaQuery<S> query, Root<E> root, Specification<E> spec, List<Selection<?>> selectionList, LockModeType lockMode) {
	if (selectionList != null) {
		Predicate predicate = spec.toPredicate(root, query, builder);
		if (predicate != null) {
			query.where(predicate);
		}
		query.multiselect(selectionList);
		return (S) em.createQuery(query).setLockMode(lockMode).getSingleResult();
	}
	return null;
}
 
Example 13
Source File: Disjunction.java    From specification-arg-resolver with Apache License 2.0 5 votes vote down vote up
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    Specification<T> combinedSpecs = null;
    for (Specification<T> spec : innerSpecs) {
        if (combinedSpecs == null) {
            combinedSpecs = Specification.where(spec);
        } else {
            combinedSpecs = combinedSpecs.or(spec);
        }
    }
    return combinedSpecs.toPredicate(root, query, cb);
}
 
Example 14
Source File: FindPageSpecificationInterceptor.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    final Object[] parameterValues = context.getParameterValues();
    if (parameterValues.length != 2) {
        throw new IllegalStateException("Expected exactly 2 arguments to method");
    }
    final Object parameterValue = parameterValues[0];
    final Object pageableObject = parameterValues[1];
    if (parameterValue instanceof Specification) {
        Specification specification = (Specification) parameterValue;
        final EntityManager entityManager = jpaOperations.getCurrentEntityManager();
        final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        final CriteriaQuery<Object> query = criteriaBuilder.createQuery((Class<Object>) getRequiredRootEntity(context));
        final Root<Object> root = query.from((Class<Object>) getRequiredRootEntity(context));
        final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder);
        query.where(predicate);
        query.select(root);

        if (pageableObject instanceof Pageable) {
            Pageable pageable = (Pageable) pageableObject;
            final Sort sort = pageable.getSort();
            if (sort.isSorted()) {
                final List<Order> orders = QueryUtils.toOrders(sort, root, criteriaBuilder);
                query.orderBy(orders);
            }
            final TypedQuery<Object> typedQuery = entityManager
                    .createQuery(query);
            if (pageable.isUnpaged()) {
                return new PageImpl<>(
                    typedQuery
                            .getResultList()
                );
            } else {
                typedQuery.setFirstResult((int) pageable.getOffset());
                typedQuery.setMaxResults(pageable.getPageSize());
                final List<Object> results = typedQuery.getResultList();
                final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
                final Root<?> countRoot = countQuery.from(getRequiredRootEntity(context));
                final Predicate countPredicate = specification.toPredicate(root, query, criteriaBuilder);
                countQuery.where(countPredicate);
                countQuery.select(criteriaBuilder.count(countRoot));

                return new PageImpl<>(
                        results,
                        pageable,
                        entityManager.createQuery(countQuery).getSingleResult()
                );
            }

        } else {
            return new PageImpl<>(
                    entityManager
                            .createQuery(query)
                            .getResultList()
            );
        }
    } else {
        throw new IllegalArgumentException("Argument must be an instance of: " + Specification.class);
    }
}