Java Code Examples for org.springframework.data.jpa.repository.query.QueryUtils

The following examples show how to use org.springframework.data.jpa.repository.query.QueryUtils. These examples are extracted from open source projects. 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 Project: linq   Source File: LinqImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> List<T> list(Pageable pageable) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.list(pageable);
	}
	if (pageable == null) {
		return list();
	} else {
		Sort sort = pageable.getSort();
		orders.addAll(QueryUtils.toOrders(sort, root, cb));
		applyPredicateToCriteria(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		return transform(query, false);
	}
}
 
Example 2
Source Project: bdf3   Source File: LinqImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> List<T> list(Pageable pageable) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.list(pageable);
	}
	if (pageable == null) {
		return list();
	} else {
		Sort sort = pageable.getSort();
		orders.addAll(QueryUtils.toOrders(sort, root, cb));
		applyPredicateToCriteria(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		return transform(query, false);
	}
}
 
Example 3
@Override
protected Query doCreateQuery(Object[] values) {
    String nativeQuery = getQuery(values);
    JpaParameters parameters = getQueryMethod().getParameters();
    ParameterAccessor accessor = new ParametersParameterAccessor(parameters, values);
    String sortedQueryString = QueryUtils
            .applySorting(nativeQuery, accessor.getSort(), QueryUtils.detectAlias(nativeQuery));
    Query query = bind(createJpaQuery(sortedQueryString), values);
    if (parameters.hasPageableParameter()) {
        Pageable pageable = (Pageable) (values[parameters.getPageableIndex()]);
        if (pageable != null) {
            query.setFirstResult((int) pageable.getOffset());
            query.setMaxResults(pageable.getPageSize());
        }
    }
    return query;
}
 
Example 4
Source Project: linq   Source File: JpaUtil.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
/**
 * 分页条件查询
 * @param cq 条件
 * @param pageable 分页信息
 * @param <T> 领域类(实体类)范型
 * @return 分页结果
 */
public static <T> Page<T> findAll(CriteriaQuery<T> cq, Pageable pageable) {
	Class<T> domainClass = cq.getResultType();
	Root<T> root;
	if (CollectionUtils.isEmpty(cq.getRoots())) {
		root = cq.from(domainClass);
	} else {
		root = (Root<T>) cq.getRoots().iterator().next();
	}
	EntityManager em = getEntityManager(domainClass);
	if (pageable == null) {
		List<T> list = findAll(cq);
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		cq.orderBy(QueryUtils.toOrders(sort, root, em.getCriteriaBuilder()));
		TypedQuery<T> query = em.createQuery(cq);
		
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		Long total = count(cq);
		List<T> content = total > pageable.getOffset() ? query.getResultList() : Collections.<T> emptyList();

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 5
Source Project: linq   Source File: LinqImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> Page<T> paging(Pageable pageable) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.paging(pageable);
	}
	List<T> list;
	if (pageable == null) {
		list = list();
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		if (sort != null) {
			orders.addAll(QueryUtils.toOrders(sort, root, cb));
		}
		applyPredicateToCriteria(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		Long total = JpaUtil.count(criteria);
		List<T> content = Collections.<T> emptyList();
		if (total > pageable.getOffset()) {
			content = transform(query, false);
		}

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 6
Source Project: bdf3   Source File: LinqImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> org.springframework.data.domain.Page<T> paging(Pageable pageable) {
	if (parent != null) {
		beforeExecute(sq);
		return parent.paging(pageable);
	}
	List<T> list;
	if (pageable == null) {
		list = list();
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		orders.addAll(QueryUtils.toOrders(sort, root, cb));
		beforeExecute(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		Long total = JpaUtil.count(criteria);
		List<T> content = Collections.<T> emptyList();
		if (total > pageable.getOffset()) {
			content = transform(query, false);
		}

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 7
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 8
Source Project: es   Source File: SimpleBaseRepository.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads the given {@link javax.persistence.TypedQuery} into a {@link org.springframework.data.domain.Page} applying the given {@link org.springframework.data.domain.Pageable} and
 * {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param query    must not be {@literal null}.
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return
 */
private Page<M> readPage(TypedQuery<M> query, Pageable pageable, Specification<M> spec) {

    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    Long total = QueryUtils.executeCountQuery(getCountQuery(spec));
    List<M> content = total > pageable.getOffset() ? query.getResultList() : Collections.<M>emptyList();

    return new PageImpl<M>(content, pageable, total);
}
 
Example 9
@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);
    }
}
 
Example 10
@Override
public Page<AuditRecord> findByActionTypeAndOperationTypeAndDate(AuditOperationType[] operations,
		AuditActionType[] actions, Instant fromDate, Instant toDate, Pageable pageable) {

	final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
	final CriteriaQuery<AuditRecord> query = cb.createQuery(AuditRecord.class);
	final Root<AuditRecord> auditRecordRoot = query.from(AuditRecord.class);

	final Path<AuditActionType> auditAction = auditRecordRoot.get("auditAction");
	final Path<AuditOperationType> auditOperation = auditRecordRoot.get("auditOperation");
	final Path<Instant> createdOn = auditRecordRoot.get("createdOn");

	final Predicate datePredicate;
	if (fromDate != null && toDate == null) {
		datePredicate = cb.greaterThanOrEqualTo(createdOn, fromDate);
	}
	else if (fromDate == null && toDate != null) {
		datePredicate = cb.lessThanOrEqualTo(createdOn, toDate);
	}
	else if (fromDate != null && toDate != null) {
		datePredicate = cb.between(createdOn, fromDate, toDate);
	}
	else {
		datePredicate = null;
	}

	final List<Predicate> auditActionPredicates = new ArrayList<>();
	if (actions != null && actions.length > 0) {
		for (AuditActionType action : actions) {
			auditActionPredicates.add(cb.equal(auditAction, action));
		}
	}

	final List<Predicate> auditOperationsPredicates = new ArrayList<>();
	if (operations != null && operations.length > 0) {
		for (AuditOperationType operation : operations) {
			auditOperationsPredicates.add(cb.equal(auditOperation, operation));
		}
	}

	final List<Predicate> finalQueryPredicates = new ArrayList<>();
	if (!auditActionPredicates.isEmpty()) {
		final Predicate auditActionPredicatesOr = cb.or(auditActionPredicates.toArray(new Predicate[0]));
		finalQueryPredicates.add(auditActionPredicatesOr);
	}
	if (datePredicate != null) {
		finalQueryPredicates.add(datePredicate);
	}
	if (!auditOperationsPredicates.isEmpty()) {
		final Predicate auditOperationsPredicatesOr = cb.or(auditOperationsPredicates.toArray(new Predicate[0]));
		finalQueryPredicates.add(auditOperationsPredicatesOr);
	}

	final CriteriaQuery<AuditRecord> select = query.select(auditRecordRoot);

	if (!finalQueryPredicates.isEmpty()) {
		select.where(finalQueryPredicates.toArray(new Predicate[0]));
	}

	if (pageable.getSort().isUnsorted()) {
		select.orderBy(QueryUtils.toOrders(pageable.getSort().and(Sort.by("id")).ascending(), auditRecordRoot, cb));
	}
	else {
		select.orderBy(QueryUtils.toOrders(pageable.getSort(), auditRecordRoot, cb));
	}

	final TypedQuery<AuditRecord> typedQuery = entityManager.createQuery(select);
	typedQuery.setFirstResult((int) pageable.getOffset());
	typedQuery.setMaxResults(pageable.getPageSize());

	final List<AuditRecord> resultList = typedQuery.getResultList();

	final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
	countQuery.select(cb.count(countQuery.from(AuditRecord.class)));

	if (!finalQueryPredicates.isEmpty()) {
		countQuery.where(finalQueryPredicates.toArray(new Predicate[0]));
	}

	final Long totalCount = entityManager.createQuery(countQuery)
			  .getSingleResult();

	return new PageImpl<>(resultList, pageable, totalCount);
}