List of usage examples for javax.persistence.criteria CriteriaQuery distinct
CriteriaQuery<T> distinct(boolean distinct);
From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java
@Override public void afterPropertiesSet() throws Exception { this.nameParameter = this.createParameterExpression(String.class, "name"); this.findAllAccountsQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<LocalAccountPersonImpl>>() { @Override//from w w w .j a va2 s.co m public CriteriaQuery<LocalAccountPersonImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb .createQuery(LocalAccountPersonImpl.class); final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery .from(LocalAccountPersonImpl.class); accountRoot.fetch(LocalAccountPersonImpl_.attributes, JoinType.LEFT) .fetch(LocalAccountPersonAttributeImpl_.values, JoinType.LEFT); criteriaQuery.select(accountRoot); return criteriaQuery; } }); this.findAccountByNameQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<LocalAccountPersonImpl>>() { @Override public CriteriaQuery<LocalAccountPersonImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb .createQuery(LocalAccountPersonImpl.class); final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery .from(LocalAccountPersonImpl.class); accountRoot.fetch(LocalAccountPersonImpl_.attributes, JoinType.LEFT) .fetch(LocalAccountPersonAttributeImpl_.values, JoinType.LEFT); criteriaQuery.select(accountRoot); criteriaQuery.where(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), nameParameter)); return criteriaQuery; } }); this.findAvailableAttributesQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<String>>() { @Override public CriteriaQuery<String> apply(CriteriaBuilder cb) { final CriteriaQuery<String> criteriaQuery = cb.createQuery(String.class); final Root<LocalAccountPersonAttributeImpl> accountRoot = criteriaQuery .from(LocalAccountPersonAttributeImpl.class); criteriaQuery.select(accountRoot.get(LocalAccountPersonAttributeImpl_.name)); criteriaQuery.distinct(true); return criteriaQuery; } }); }
From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java
@Override public List<ILocalAccountPerson> getPeople(LocalAccountQuery query) { final EntityManager entityManager = this.getEntityManager(); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb.createQuery(LocalAccountPersonImpl.class); final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery.from(LocalAccountPersonImpl.class); final CollectionJoin<LocalAccountPersonImpl, LocalAccountPersonAttributeImpl> attributes = accountRoot .join(LocalAccountPersonImpl_.attributes); final ListJoin<LocalAccountPersonAttributeImpl, String> attributeValues = attributes .join(LocalAccountPersonAttributeImpl_.values); //Due to the joins multiple rows are returned for each result criteriaQuery.distinct(true); criteriaQuery.select(accountRoot);/*from www . j ava2 s . com*/ final List<Predicate> whereParts = new LinkedList<Predicate>(); final Map<Parameter<String>, String> params = new LinkedHashMap<Parameter<String>, String>(); // if a username has been specified, append it to the query if (query.getName() != null) { whereParts.add(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), this.nameParameter)); params.put(this.nameParameter, query.getName()); } //Build Predicate for each attribute being queried int paramCount = 0; for (Map.Entry<String, List<String>> entry : query.getAttributes().entrySet()) { final List<String> values = entry.getValue(); if (values == null) { continue; } //For each value create a Predicate checking the attribute name and value together for (final String value : values) { if (StringUtils.isBlank(value)) { continue; } //Create Parameter objects for the name and value, stick them in the params map for later use final ParameterExpression<String> nameParam = this.createParameterExpression(String.class, "attrName" + paramCount); final ParameterExpression<String> valueParam = this.createParameterExpression(String.class, "attrValue" + paramCount); params.put(nameParam, entry.getKey()); params.put(valueParam, "%" + value.toLowerCase() + "%"); //Build the and(eq, like) predicate and add it to the list of predicates for the where clause whereParts.add(cb.and(cb.equal(attributes.get(LocalAccountPersonAttributeImpl_.name), nameParam), cb.like(cb.lower(attributeValues.as(String.class)), valueParam))); paramCount++; } } //Add the Predicates to the where clause criteriaQuery.where(cb.or(whereParts.toArray(new Predicate[whereParts.size()]))); //Create the query final TypedQuery<LocalAccountPersonImpl> jpaQuery = this.createCachedQuery(criteriaQuery); //Add all of the stored up parameters to the query for (Map.Entry<Parameter<String>, String> entry : params.entrySet()) { final Parameter<String> parameter = entry.getKey(); final String value = entry.getValue(); jpaQuery.setParameter(parameter, value); } final List<LocalAccountPersonImpl> accounts = jpaQuery.getResultList(); return new ArrayList<ILocalAccountPerson>(accounts); }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
@Override public List<Product> readProductsByIds(List<Long> productIds) { if (productIds == null || productIds.size() == 0) { return null; }//from w w w . ja va2 s. c o m if (productIds.size() > 100) { logger.warn("Not recommended to use the readProductsByIds method for long lists of productIds, since " + "Hibernate is required to transform the distinct results. The list of requested" + "product ids was (" + productIds.size() + ") in length."); } // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); Root<ProductImpl> product = criteria.from(ProductImpl.class); FetchParent fetchParent = product.fetch("defaultSku", JoinType.LEFT); if (!dialectHelper.isOracle() && !dialectHelper.isSqlServer()) { fetchParent.fetch("skuMedia", JoinType.LEFT); } criteria.select(product); // We only want results that match the product IDs criteria.where(product.get("id").as(Long.class).in( sandBoxHelper.mergeCloneIds(ProductImpl.class, productIds.toArray(new Long[productIds.size()])))); if (!dialectHelper.isOracle() && !dialectHelper.isSqlServer()) { criteria.distinct(true); } TypedQuery<Product> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); }
From source file:org.easy.criteria.BaseDAO.java
/** * Find all entities of the given type that are associated with this parent. * @param childClass/* w w w. j av a 2 s . c om*/ * @param parent * @return */ public <A, E> List<A> findByAssociation(Class<A> forClass, SingularAttribute<A, E> associationAttribute, E associatedWith) { if (log.isTraceEnabled()) log.trace("findAssociatedEntity: "); CriteriaBuilder criteriaBuilder = _entityManager.getCriteriaBuilder(); CriteriaQuery<A> criteria = criteriaBuilder.createQuery(forClass); log.debug("Root :" + forClass.getSimpleName()); Root<A> child = criteria.from(forClass); criteria.distinct(true); criteria.where(criteriaBuilder.equal(child.get(associationAttribute), associatedWith)); TypedQuery<A> query = _entityManager.createQuery(criteria); return query.getResultList(); }
From source file:org.easy.criteria.BaseDAO.java
/** * @param forClass/*w ww. j a va 2s .c o m*/ * @param attributeToMatch * @param value * @return */ public <E, V> List<E> findByProperty(Class<E> forClass, SingularAttribute<E, V> attributeToMatch, V value) { if (log.isTraceEnabled()) log.trace("findByProperty: "); Preconditions.checkNotNull(forClass); CriteriaBuilder criteriaBuilder = _entityManager.getCriteriaBuilder(); CriteriaQuery<E> criteria = criteriaBuilder.createQuery(forClass); log.debug("Root :" + forClass.getSimpleName()); Root<E> child = criteria.from(forClass); criteria.distinct(true); Predicate predicate = criteriaBuilder.equal(child.get(attributeToMatch), value); criteria.where(predicate); TypedQuery<E> query = _entityManager.createQuery(criteria); return query.getResultList(); }
From source file:org.easy.criteria.CriteriaProcessor.java
/** * Finds all entities that satisfied the given criteria. This ignores the * "Select" clause. If you need to selected some specific columns then use * "findAllTuple" API./*from w w w . j av a2 s . c om*/ * * @param criteria * - A restriction criteria or NULL to get every thing. * @param distinct * @param startIndex * - Pass 0 or less to disable paging. * @param maxResult * - Pass 0 or less to disable paging. * @param lockMode * - Pass NULL if your are not managing transaction. * LockModeType.NONE will through exception if no transaction is * active. * @return - A list of entities or an empty list if no result were found. */ public <T> List<T> findAllEntity(CriteriaComposer<T> criteria, boolean distinct, QueryProperties properties) { log.trace("CriteriaProcessor.findAllEntity"); Preconditions.checkNotNull(criteria); Class<T> forClass = criteria.getEntityClass(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(forClass); log.debug("root =" + forClass.getName()); Root<T> root = criteriaQuery.from(forClass); criteriaQuery.distinct(distinct); List<Predicate> wherePredicates = new ArrayList<Predicate>(); Map<Integer, Order> orderBy = new HashMap<Integer, Order>(0); if (criteria != null) { criteria.generateJoins(root); criteria.generateWhere(criteriaBuilder, wherePredicates); criteria.generateOrderBy(criteriaBuilder, orderBy); } criteriaQuery.where(wherePredicates.toArray(new Predicate[wherePredicates.size()])); // Order by if (orderBy != null && orderBy.size() > 0) { Order[] orderByList = new Order[orderBy.size()]; orderBy.values().toArray(orderByList); criteriaQuery.orderBy(orderByList); } TypedQuery<T> query = entityManager.createQuery(criteriaQuery); if (properties != null) properties.applyProperties(query); List<T> result = query.getResultList(); if (result == null) result = new ArrayList<T>(0); log.debug("CriteriaProcessor.findAllEntity result size=" + result.size()); return result; }
From source file:org.eclipse.hawkbit.repository.jpa.JpaTargetManagement.java
@Override public Slice<Target> findTargetsAllOrderByLinkedDistributionSet(final Pageable pageable, final Long orderByDistributionId, final FilterParams filterParams) { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<JpaTarget> query = cb.createQuery(JpaTarget.class); final Root<JpaTarget> targetRoot = query.from(JpaTarget.class); // select case expression to retrieve the case value as a column to be // able to order based on // this column, installed first,... final Expression<Object> selectCase = cb.selectCase() .when(cb.equal(targetRoot.get(JpaTarget_.installedDistributionSet).get(JpaDistributionSet_.id), orderByDistributionId), 1) .when(cb.equal(targetRoot.get(JpaTarget_.assignedDistributionSet).get(JpaDistributionSet_.id), orderByDistributionId), 2) .otherwise(100);/*from w w w . jav a2 s .co m*/ // multiselect statement order by the select case and controllerId query.distinct(true); // build the specifications and then to predicates necessary by the // given filters final Predicate[] specificationsForMultiSelect = specificationsToPredicate( buildSpecificationList(filterParams), targetRoot, query, cb); // if we have some predicates then add it to the where clause of the // multiselect if (specificationsForMultiSelect.length > 0) { query.where(specificationsForMultiSelect); } // add the order to the multi select first based on the selectCase query.orderBy(cb.asc(selectCase), cb.desc(targetRoot.get(JpaTarget_.id))); // the result is a Object[] due the fact that the selectCase is an extra // column, so it cannot // be mapped directly to a Target entity because the selectCase is not a // attribute of the // Target entity, the the Object array contains the Target on the first // index (case of the // multiselect order) of the array and // the 2nd contains the selectCase int value. final int pageSize = pageable.getPageSize(); final List<JpaTarget> resultList = entityManager.createQuery(query).setFirstResult(pageable.getOffset()) .setMaxResults(pageSize + 1).getResultList(); final boolean hasNext = resultList.size() > pageSize; return new SliceImpl<>(Collections.unmodifiableList(resultList), pageable, hasNext); }
From source file:org.jboss.pressgang.ccms.filter.utils.JPAUtils.java
/** * Copy Criteria without Selection//from w w w. j a v a 2s . co m * * @param from source Criteria * @param to destination Criteria */ public static void copyCriteriaNoSelection(CriteriaQuery<?> from, CriteriaQuery<?> to) { // Copy Roots for (Root<?> root : from.getRoots()) { Root<?> dest = to.from(root.getJavaType()); dest.alias(getOrCreateAlias(root)); copyJoins(root, dest); } if (from.getGroupList() != null) to.groupBy(from.getGroupList()); to.distinct(from.isDistinct()); if (from.getGroupRestriction() != null) to.having(from.getGroupRestriction()); if (from.getRestriction() != null) to.where(from.getRestriction()); if (from.getOrderList() != null) to.orderBy(from.getOrderList()); }
From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java
@Override public List<RuleBaseValues> search(String docTypeName, String ruleId, String ruleTemplateId, String ruleDescription, String groupId, String principalId, Boolean delegateRule, Boolean activeInd, Map extensionValues, String workflowIdDirective) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<RuleBaseValues> cq = cb.createQuery(RuleBaseValues.class); Root<RuleBaseValues> root = cq.from(RuleBaseValues.class); List<javax.persistence.criteria.Predicate> predicates = getSearchCriteria(root, cq, docTypeName, ruleTemplateId, ruleDescription, delegateRule, activeInd, extensionValues); if (ruleId != null) { predicates.add(cb.equal(root.get("id"), ruleId)); }/*w w w . j a v a 2 s.c o m*/ if (groupId != null) { predicates.add(cb.in(root.get("id")).value(getRuleResponsibilitySubQuery(groupId, cq))); } Collection<String> kimGroupIds = new HashSet<String>(); Boolean searchUser = Boolean.FALSE; Boolean searchUserInWorkgroups = Boolean.FALSE; if ("group".equals(workflowIdDirective)) { searchUserInWorkgroups = Boolean.TRUE; } else if (StringUtils.isBlank(workflowIdDirective)) { searchUser = Boolean.TRUE; searchUserInWorkgroups = Boolean.TRUE; } else { searchUser = Boolean.TRUE; } if (!org.apache.commons.lang.StringUtils.isEmpty(principalId) && searchUserInWorkgroups) { Principal principal = null; principal = KimApiServiceLocator.getIdentityService().getPrincipal(principalId); if (principal == null) { throw new RiceRuntimeException("Failed to locate user for the given principal id: " + principalId); } kimGroupIds = KimApiServiceLocator.getGroupService().getGroupIdsByPrincipalId(principalId); } Subquery<RuleResponsibilityBo> subquery = addResponsibilityCriteria(cq, kimGroupIds, principalId, searchUser, searchUserInWorkgroups); if (subquery != null) { predicates.add(cb.in(root.get("id")).value(subquery)); } cq.distinct(true); javax.persistence.criteria.Predicate[] preds = predicates .toArray(new javax.persistence.criteria.Predicate[predicates.size()]); cq.where(preds); TypedQuery<RuleBaseValues> q = getEntityManager().createQuery(cq); return q.getResultList(); }
From source file:org.sparkcommerce.core.catalog.dao.ProductDaoImpl.java
@Override public List<Product> readProductsByIds(List<Long> productIds) { if (productIds == null || productIds.size() == 0) { return null; }//from w w w . j a va 2 s. c o m if (productIds.size() > 100) { logger.warn("Not recommended to use the readProductsByIds method for long lists of productIds, since " + "Hibernate is required to transform the distinct results. The list of requested" + "product ids was (" + productIds.size() + ") in length."); } // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); Root<ProductImpl> product = criteria.from(ProductImpl.class); FetchParent fetchParent = product.fetch("defaultSku", JoinType.LEFT); if (!dialectHelper.isOracle() && !dialectHelper.isSqlServer()) { fetchParent.fetch("skuMedia", JoinType.LEFT); } criteria.select(product); // We only want results that match the product IDs criteria.where(product.get("id").as(Long.class).in(sandBoxHelper.mergeCloneIds(em, ProductImpl.class, productIds.toArray(new Long[productIds.size()])))); if (!dialectHelper.isOracle() && !dialectHelper.isSqlServer()) { criteria.distinct(true); } TypedQuery<Product> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); }