List of usage examples for javax.persistence.criteria CriteriaQuery orderBy
CriteriaQuery<T> orderBy(List<Order> o);
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected void attachOrderBy(SearchCriteria searchCriteria, From<?, ? extends Product> product, Path<? extends Sku> sku, CriteriaQuery<?> criteria) { if (StringUtils.isNotBlank(searchCriteria.getSortQuery())) { CriteriaBuilder builder = em.getCriteriaBuilder(); List<Order> sorts = new ArrayList<Order>(); String sortQueries = searchCriteria.getSortQuery(); for (String sortQuery : sortQueries.split(",")) { String[] sort = sortQuery.split(" "); if (sort.length == 2) { String key = sort[0]; boolean asc = sort[1].toLowerCase().contains("asc"); // Determine whether we should use the product path or the sku path Path<?> pathToUse; if (key.contains("defaultSku.")) { pathToUse = sku;/*from w w w. j a va 2 s . c o m*/ key = key.substring("defaultSku.".length()); } else if (key.contains("product.")) { pathToUse = product; key = key.substring("product.".length()); } else { // We don't know which path this facet is built on - resolves previous bug that attempted // to attach search facet to any query parameter continue; } if (asc) { sorts.add(builder.asc(pathToUse.get(key))); } else { sorts.add(builder.desc(pathToUse.get(key))); } } } criteria.orderBy(sorts.toArray(new Order[sorts.size()])); } }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected CriteriaQuery<Product> getCriteriaForActiveProducts(Date currentDate) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); // The root of our search is Product Root<ProductImpl> product = criteria.from(ProductImpl.class); // We need to filter on active date on the sku Join<Product, Sku> sku = product.join("defaultSku"); product.fetch("defaultSku"); // Product objects are what we want back criteria.select(product);/* www . j a va 2s.c o m*/ // Ensure the product is currently active List<Predicate> restrictions = new ArrayList<Predicate>(); attachActiveRestriction(currentDate, product, sku, restrictions); // Add the restrictions to the criteria query criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); //Add ordering so that paginated queries are consistent criteria.orderBy(builder.asc(product.get("id"))); return criteria; }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.CriteriaTranslatorImpl.java
@SuppressWarnings("unchecked") protected TypedQuery<Serializable> constructQuery(DynamicEntityDao dynamicEntityDao, String ceilingEntity, List<FilterMapping> filterMappings, boolean isCount, boolean isMax, Integer firstResult, Integer maxResults, String maxField) { CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder(); Class<Serializable> ceilingMarker; try {//from ww w .j a v a 2s .c o m ceilingMarker = (Class<Serializable>) Class.forName(ceilingEntity); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } Class<Serializable> securityRoot = rowSecurityService.getFetchRestrictionRoot( adminSecurityService.getPersistentAdminUser(), ceilingMarker, filterMappings); if (securityRoot != null) { ceilingMarker = securityRoot; } Class<Serializable> ceilingClass = determineRoot(dynamicEntityDao, ceilingMarker, filterMappings); CriteriaQuery<Serializable> criteria = criteriaBuilder.createQuery(ceilingMarker); Root<Serializable> original = criteria.from(ceilingClass); if (isCount) { criteria.select(criteriaBuilder.count(original)); } else if (isMax) { criteria.select(criteriaBuilder.max((Path<Number>) ((Object) original.get(maxField)))); } else { criteria.select(original); } List<Predicate> restrictions = new ArrayList<Predicate>(); List<Order> sorts = new ArrayList<Order>(); addRestrictions(ceilingEntity, filterMappings, criteriaBuilder, original, restrictions, sorts, criteria); criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); if (!isCount && !isMax) { criteria.orderBy(sorts.toArray(new Order[sorts.size()])); //If someone provides a firstResult value, then there is generally pagination going on. //In order to produce consistent results, especially with certain databases such as PostgreSQL, //there has to be an "order by" clause. We'll add one here if we can. if (firstResult != null && sorts.isEmpty()) { Map<String, Object> idMetaData = dynamicEntityDao.getIdMetadata(ceilingClass); if (idMetaData != null) { Object idFldName = idMetaData.get("name"); Object type = idMetaData.get("type"); if ((idFldName instanceof String) && (type instanceof SingleColumnType)) { criteria.orderBy(criteriaBuilder.asc(original.get((String) idFldName))); } } } } TypedQuery<Serializable> response = dynamicEntityDao.getStandardEntityManager().createQuery(criteria); if (!isCount && !isMax) { addPaging(response, firstResult, maxResults); } return response; }
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 www .ja va2s .c o m*/ * * @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.easy.criteria.CriteriaProcessor.java
/** * Finds all the tuples for the given criteria. Make sure you have provided * columns information in CriteriaContainer that you want in this tuple * result-set.// ww w .ja va 2 s . com * * @param criteria * - Criteria that you want to apply to this search. * @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 tuples or an empty list if no result were found. */ public <T> List<Tuple> findAllTuple(CriteriaComposer<T> criteria, boolean distinct, QueryProperties properties) { log.trace("CriteriaProcessor.findAllTuple"); Preconditions.checkNotNull(criteria); Class<T> forClass = criteria.getEntityClass(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createQuery(Tuple.class); log.debug("root =" + forClass.getName()); Root<T> root = criteriaQuery.from(forClass); List<Predicate> wherePredicates = new ArrayList<Predicate>(); List<Selection<?>> selectPredicates = new ArrayList<Selection<?>>(); Map<Integer, Order> orderByPredicates = new HashMap<Integer, Order>(0); Map<Integer, Expression<?>> groupByPredicates = new HashMap<Integer, Expression<?>>(0); List<Predicate> havingPredicates = new ArrayList<Predicate>(0); if (criteria != null) { criteria.generateJoins(root); criteria.generateSelect(criteriaBuilder, selectPredicates); criteria.generateGroupBy(criteriaBuilder, groupByPredicates); criteria.generateWhere(criteriaBuilder, wherePredicates); criteria.generateOrderBy(criteriaBuilder, orderByPredicates); criteria.generateHaving(criteriaBuilder, havingPredicates); } Preconditions.checkState(selectPredicates != null); Preconditions.checkArgument(selectPredicates.size() > 0, "No column name found for select clause. " + "Atleast one should be provided for Tuple result. Consider using findAllEntity instead."); criteriaQuery.multiselect(selectPredicates); criteriaQuery.where(wherePredicates.toArray(new Predicate[wherePredicates.size()])); if (orderByPredicates != null && orderByPredicates.size() > 0) { Order[] orderByList = new Order[orderByPredicates.size()]; orderByPredicates.values().toArray(orderByList); criteriaQuery.orderBy(orderByList); } if (groupByPredicates != null && groupByPredicates.size() > 0) { Expression<?>[] groupByList = new Expression<?>[groupByPredicates.size()]; groupByPredicates.values().toArray(groupByList); criteriaQuery.groupBy(groupByList); } criteriaQuery.having(havingPredicates.toArray(new Predicate[havingPredicates.size()])); TypedQuery<Tuple> query = entityManager.createQuery(criteriaQuery); if (properties != null) properties.applyProperties(query); List<Tuple> tuples = query.getResultList(); if (tuples == null) tuples = new ArrayList<Tuple>(0); log.debug("CriteriaProcessor.findAllEntity result size=" + tuples.size()); return tuples; }
From source file:org.eclipse.jubula.client.core.persistence.TestResultPM.java
/** * @param session The session in which to execute the Persistence (JPA / EclipseLink) query. * @param summaryId The database ID of the summary for which to compute the * corresponding Test Result nodes. * @return the Test Result nodes associated with the given Test Result * Summary, sorted by sequence (ascending). *//*from w ww . jav a 2 s. c om*/ @SuppressWarnings({ "unchecked", "rawtypes" }) public static List<ITestResultPO> computeTestResultListForSummary(EntityManager session, Long summaryId) { CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery query = builder.createQuery(); Root from = query.from(PoMaker.getTestResultClass()); query.orderBy(builder.asc(from.get("keywordSequence"))) //$NON-NLS-1$ .select(from).where(builder.equal(from.get("internalTestResultSummaryID"), summaryId)); //$NON-NLS-1$ return session.createQuery(query).getResultList(); }
From source file:org.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java
public TypedQuery<Connection> buildLastConnections() { EntityManager em = EntityManagerHolder.get(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Connection> criteria = cb.createQuery(Connection.class); Root<Connection> connection = criteria.from(Connection.class); Predicate predicate = null;/* w w w. jav a2 s. c o m*/ //owner if (this.owner != null) { predicate = cb.equal(connection.get(Connection_.senderId), owner.getId()); } //status if (this.status != null) { predicate = cb.and(predicate, cb.equal(connection.get(Connection_.status), this.status)); } CriteriaQuery<Connection> select = criteria.select(connection).distinct(true); select.where(predicate); select.orderBy(cb.desc(connection.<Long>get(Connection_.id))); TypedQuery<Connection> typedQuery = em.createQuery(select); if (this.limit > 0) { typedQuery.setFirstResult((int) offset); typedQuery.setMaxResults((int) limit); } return typedQuery; }
From source file:org.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java
public TypedQuery<Connection> buildFilter() { EntityManager em = EntityManagerHolder.get(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Connection> criteria = cb.createQuery(Connection.class); Root<Connection> connection = criteria.from(Connection.class); Join<Connection, Profile> receiver = connection.join(Connection_.receiver); ///* ww w . j ava2 s. c om*/ CriteriaQuery<Connection> select = criteria.select(connection); select.where(buildPredicateFilter(cb, receiver, connection)); select.orderBy(cb.asc(receiver.get(Profile_.fullName))); // TypedQuery<Connection> typedQuery = em.createQuery(select); if (this.limit > 0) { typedQuery.setFirstResult((int) offset); typedQuery.setMaxResults((int) limit); } // return typedQuery; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}//from w w w.j a va 2 s .co m */ @Override public List<NamespaceKey> getNamespaces() { // Create the criteria builder and a tuple style criteria query. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<String> criteria = builder.createQuery(String.class); // The criteria root is the business object definition. Root<NamespaceEntity> namespaceEntity = criteria.from(NamespaceEntity.class); // Get the columns. Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code); // Add the select clause. criteria.select(namespaceCodeColumn); // Add the order by clause. criteria.orderBy(builder.asc(namespaceCodeColumn)); // Run the query to get a list of namespace codes back. List<String> namespaceCodes = entityManager.createQuery(criteria).getResultList(); // Populate the "keys" objects from the returned namespace codes. List<NamespaceKey> namespaceKeys = new ArrayList<>(); for (String namespaceCode : namespaceCodes) { namespaceKeys.add(new NamespaceKey(namespaceCode)); } return namespaceKeys; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}//ww w . j av a2s . c om */ @Override public List<FileTypeKey> getFileTypes() { // Create the criteria builder and a tuple style criteria query. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<String> criteria = builder.createQuery(String.class); // The criteria root is the file type. Root<FileTypeEntity> fileTypeEntity = criteria.from(FileTypeEntity.class); // Get the columns. Path<String> fileTypeCodeColumn = fileTypeEntity.get(FileTypeEntity_.code); // Add the select clause. criteria.select(fileTypeCodeColumn); // Add the order by clause. criteria.orderBy(builder.asc(fileTypeCodeColumn)); // Run the query to get a list of file type codes back. List<String> fileTypeCodes = entityManager.createQuery(criteria).getResultList(); // Populate the "keys" objects from the returned file type codes. List<FileTypeKey> fileTypeKeys = new ArrayList<>(); for (String fileTypeCode : fileTypeCodes) { fileTypeKeys.add(new FileTypeKey(fileTypeCode)); } return fileTypeKeys; }