List of usage examples for javax.persistence.criteria CriteriaQuery orderBy
CriteriaQuery<T> orderBy(List<Order> o);
From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java
/** * Finds all {@link AlertHistoryEntity} that match the provided * {@link AlertHistoryRequest}. This method will make JPA do the heavy lifting * of providing a slice of the result set. * * @param request//ww w.j a va 2 s.com * @return */ @RequiresSession public List<AlertHistoryEntity> findAll(AlertHistoryRequest request) { EntityManager entityManager = m_entityManagerProvider.get(); // convert the Ambari predicate into a JPA predicate HistoryPredicateVisitor visitor = new HistoryPredicateVisitor(); PredicateHelper.visit(request.Predicate, visitor); CriteriaQuery<AlertHistoryEntity> query = visitor.getCriteriaQuery(); javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate(); if (null != jpaPredicate) { query.where(jpaPredicate); } // sorting JpaSortBuilder<AlertHistoryEntity> sortBuilder = new JpaSortBuilder<AlertHistoryEntity>(); List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor); query.orderBy(sortOrders); // pagination TypedQuery<AlertHistoryEntity> typedQuery = entityManager.createQuery(query); if (null != request.Pagination) { typedQuery.setFirstResult(request.Pagination.getOffset()); typedQuery.setMaxResults(request.Pagination.getPageSize()); } return m_daoUtils.selectList(typedQuery); }
From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java
/** * Finds all {@link AlertCurrentEntity} that match the provided * {@link AlertCurrentRequest}. This method will make JPA do the heavy lifting * of providing a slice of the result set. * * @param request//ww w . j a va 2 s . c o m * @return */ @Transactional public List<AlertCurrentEntity> findAll(AlertCurrentRequest request) { EntityManager entityManager = m_entityManagerProvider.get(); // convert the Ambari predicate into a JPA predicate CurrentPredicateVisitor visitor = new CurrentPredicateVisitor(); PredicateHelper.visit(request.Predicate, visitor); CriteriaQuery<AlertCurrentEntity> query = visitor.getCriteriaQuery(); javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate(); if (null != jpaPredicate) { query.where(jpaPredicate); } // sorting JpaSortBuilder<AlertCurrentEntity> sortBuilder = new JpaSortBuilder<AlertCurrentEntity>(); List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor); query.orderBy(sortOrders); // pagination TypedQuery<AlertCurrentEntity> typedQuery = entityManager.createQuery(query); if (null != request.Pagination) { // prevent JPA errors when -1 is passed in by accident int offset = request.Pagination.getOffset(); if (offset < 0) { offset = 0; } typedQuery.setFirstResult(offset); typedQuery.setMaxResults(request.Pagination.getPageSize()); } List<AlertCurrentEntity> alerts = m_daoUtils.selectList(typedQuery); // if caching is enabled, replace results with cached values when present if (m_configuration.isAlertCacheEnabled()) { alerts = supplementWithCachedAlerts(alerts); } return alerts; }
From source file:org.apache.openmeetings.data.user.UserManager.java
/** * query for a list of users/*from w w w .j a v a 2 s. c o m*/ * * @param users_id * @param user_level * @param start * @param max * @param orderby * @return */ public SearchResult<User> getUsersList(long user_level, int start, int max, String orderby, boolean asc) { try { if (authLevelUtil.checkAdminLevel(user_level)) { SearchResult<User> sresult = new SearchResult<User>(); sresult.setObjectName(User.class.getName()); sresult.setRecords(usersDao.count()); // get all users CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> c = cq.from(User.class); Predicate condition = cb.equal(c.get("deleted"), false); cq.where(condition); cq.distinct(asc); if (asc) { cq.orderBy(cb.asc(c.get(orderby))); } else { cq.orderBy(cb.desc(c.get(orderby))); } TypedQuery<User> q = em.createQuery(cq); q.setFirstResult(start); q.setMaxResults(max); List<User> ll = q.getResultList(); sresult.setResult(ll); return sresult; } } catch (Exception ex2) { log.error("[getUsersList] " + ex2); } return null; }
From source file:org.apache.openmeetings.data.user.UserManager.java
/** * suche eines Bentzers//from w ww . j a va 2s. c o m * * @param user_level * @param searchstring * @param max * @param start * @return */ public List<User> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start, String orderby, boolean asc) { if (authLevelUtil.checkAdminLevel(user_level)) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> c = cq.from(User.class); Expression<String> literal = cb.literal("%" + searchstring + "%"); Path<String> path = c.get(searchcriteria); Predicate predicate = cb.like(path, literal); Predicate condition = cb.notEqual(c.get("deleted"), true); cq.where(condition, predicate); cq.distinct(asc); if (asc) { cq.orderBy(cb.asc(c.get(orderby))); } else { cq.orderBy(cb.desc(c.get(orderby))); } TypedQuery<User> q = em.createQuery(cq); q.setFirstResult(start); q.setMaxResults(max); List<User> contactsZ = q.getResultList(); return contactsZ; } catch (Exception ex2) { log.error("searchUser", ex2); } } return null; }
From source file:org.apache.ranger.service.XTrxLogService.java
@Override public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) { EntityManager em = daoMgr.getEntityManager(); CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<VXXTrxLog> selectCQ = criteriaBuilder.createQuery(VXXTrxLog.class); Root<VXXTrxLog> rootEntityType = selectCQ.from(VXXTrxLog.class); Predicate predicate = generatePredicate(searchCriteria, em, criteriaBuilder, rootEntityType); selectCQ.where(predicate);// w ww .ja va 2 s . c om if ("asc".equalsIgnoreCase(searchCriteria.getSortType())) { selectCQ.orderBy(criteriaBuilder.asc(rootEntityType.get("createTime"))); } else { selectCQ.orderBy(criteriaBuilder.desc(rootEntityType.get("createTime"))); } int startIndex = searchCriteria.getStartIndex(); int pageSize = searchCriteria.getMaxRows(); List<VXXTrxLog> resultList = em.createQuery(selectCQ).setFirstResult(startIndex).setMaxResults(pageSize) .getResultList(); List<VXTrxLog> trxLogList = new ArrayList<VXTrxLog>(); for (VXXTrxLog xTrxLog : resultList) { VXTrxLog trxLog = mapCustomViewToViewObj(xTrxLog); if (trxLog.getUpdatedBy() != null) { XXPortalUser xXPortalUser = rangerDaoManager.getXXPortalUser() .getById(Long.parseLong(trxLog.getUpdatedBy())); if (xXPortalUser != null) { trxLog.setOwner(xXPortalUser.getLoginId()); } } trxLogList.add(trxLog); } VXTrxLogList vxTrxLogList = new VXTrxLogList(); vxTrxLogList.setStartIndex(startIndex); vxTrxLogList.setPageSize(pageSize); vxTrxLogList.setVXTrxLogs(trxLogList); return vxTrxLogList; }
From source file:org.apache.rave.portal.repository.impl.JpaWidgetRepository.java
@Override public List<Widget> getByStatusAndTypeAndFreeTextSearch(WidgetStatus widgetStatus, String type, String searchTerm, int offset, int pageSize) { final CriteriaBuilder cb = manager.getCriteriaBuilder(); final CriteriaQuery<JpaWidget> query = cb.createQuery(JpaWidget.class); final Root<JpaWidget> widgetType = query.from(JpaWidget.class); query.where(getStatusAndTypeAndFreeTextPredicates(cb, widgetType, widgetStatus, type, searchTerm)); query.orderBy(getOrderByTitleAsc(cb, widgetType)); return expandProperties(getPagedResultList(manager.createQuery(query), offset, pageSize)); }
From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java
@SuppressWarnings("unchecked") public <T extends IBean> T[] findByValue(Class<T> beansInterface, String name, Object value, String orderBy, boolean ascending) { // validate entity manager transaction if (entityManager == null) { throw new IllegalStateException("Transaction not initiated or already closed"); }/*from w ww .ja v a 2 s . co m*/ // validate bean interface Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface); if (beanClass == null) { throw new IllegalArgumentException("Invalid bean interface specified"); } // get persistent beans by criteria try { // construct query criteria CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass); Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass); if (name != null) { criteriaQuery.where((value != null) ? criteriaBuilder.equal(beanRoot.get(name), value) : criteriaBuilder.isNull(beanRoot.get(name))); } if (orderBy != null) { criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy)) : criteriaBuilder.desc(beanRoot.get(orderBy))); } // invoke query Query query = entityManager.createQuery(criteriaQuery); List<? extends IBean> beansList = query.getResultList(); if ((beansList != null) && !beansList.isEmpty()) { return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size())); } } catch (Exception e) { logger.error("Unexpected exception: " + e, e); } return (T[]) Array.newInstance(beansInterface, 0); }
From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java
@SuppressWarnings("unchecked") public <T extends IBean> T[] findByValues(Class<T> beansInterface, Map<String, Object> values, String orderBy, boolean ascending) { // validate entity manager transaction if (entityManager == null) { throw new IllegalStateException("Transaction not initiated or already closed"); }/* ww w . j a v a 2 s . c o m*/ // validate bean interface Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface); if (beanClass == null) { throw new IllegalArgumentException("Invalid bean interface specified"); } // get persistent beans by criteria try { // construct query criteria CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass); Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass); if ((values != null) && !values.isEmpty()) { Predicate predicate = null; for (Map.Entry<String, Object> value : values.entrySet()) { Predicate valuePredicate = ((value.getValue() != null) ? criteriaBuilder.equal(beanRoot.get(value.getKey()), value.getValue()) : criteriaBuilder.isNull(beanRoot.get(value.getKey()))); predicate = ((predicate != null) ? criteriaBuilder.and(predicate, valuePredicate) : valuePredicate); } criteriaQuery.where(predicate); } if (orderBy != null) { criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy)) : criteriaBuilder.desc(beanRoot.get(orderBy))); } // invoke query Query query = entityManager.createQuery(criteriaQuery); List<? extends IBean> beansList = query.getResultList(); if ((beansList != null) && !beansList.isEmpty()) { return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size())); } } catch (Exception e) { logger.error("Unexpected exception: " + e, e); } return (T[]) Array.newInstance(beansInterface, 0); }
From source file:org.broadleafcommerce.cms.file.dao.StaticAssetDaoImpl.java
@Override public StaticAsset readStaticAssetByFullUrl(String fullUrl) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<StaticAsset> criteria = builder.createQuery(StaticAsset.class); Root<StaticAssetImpl> handler = criteria.from(StaticAssetImpl.class); criteria.select(handler);// w ww . j ava2s . c o m List<Predicate> restrictions = new ArrayList<Predicate>(); List<Order> sorts = new ArrayList<Order>(); restrictions.add(builder.equal(handler.get("fullUrl"), fullUrl)); try { if (queryExtensionManager != null) { queryExtensionManager.getProxy().setup(StaticAssetImpl.class, null); queryExtensionManager.getProxy().refineRetrieve(StaticAssetImpl.class, null, builder, criteria, handler, restrictions); queryExtensionManager.getProxy().refineOrder(StaticAssetImpl.class, null, builder, criteria, handler, sorts); } criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); if (!org.apache.commons.collections.CollectionUtils.isEmpty(sorts)) { criteria.orderBy(sorts); } TypedQuery<StaticAsset> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); List<StaticAsset> response = query.getResultList(); if (response.size() > 0) { return response.get(0); } return null; } finally { if (queryExtensionManager != null) { queryExtensionManager.getProxy().breakdown(StaticAssetImpl.class, null); } } }
From source file:org.broadleafcommerce.core.catalog.dao.IndexFieldCustomPersistenceHandler.java
@Override public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { FilterAndSortCriteria fieldFsc = cto.getCriteriaMap().get("field"); if (fieldFsc != null) { List<String> filterValues = fieldFsc.getFilterValues(); boolean didFilter = false; cto.getCriteriaMap().remove("field"); CriteriaBuilder builder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder(); CriteriaQuery<IndexField> criteria = builder.createQuery(IndexField.class); Root<IndexFieldImpl> root = criteria.from(IndexFieldImpl.class); criteria.select(root);/* w ww . j a v a 2s . c o m*/ // Check if we are searching for specific field names List<Predicate> restrictions = new ArrayList<Predicate>(); if (CollectionUtils.isNotEmpty(filterValues)) { restrictions.add(builder.like(root.get("field").<String>get("friendlyName"), "%" + filterValues.get(0) + "%")); didFilter = true; } // Check if this filter value has a sort direction associated with it Order order = null; for (FilterAndSortCriteria sortCriteria : cto.getCriteriaMap().values()) { if (sortCriteria.getSortDirection() != null) { Path path = root; try { // Try to find the path to the property in IndexFieldImpl String[] pathParts = sortCriteria.getPropertyId().split("\\."); for (String part : pathParts) { path = path.get(part); } // If we made it here, we have the path, set the sorting (asc/desc) if (sortCriteria.getSortAscending()) { order = builder.asc(path); } else { order = builder.desc(path); } criteria.orderBy(order); break; } catch (IllegalArgumentException e) { // This isn't an actual entity property continue; } } } criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<IndexField> query = dynamicEntityDao.getStandardEntityManager().createQuery(criteria); List<IndexField> indexFields = query.getResultList(); // Convert the result list into a list of entities PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Map<String, FieldMetadata> indexFieldMetadata = helper .getSimpleMergedProperties(IndexField.class.getName(), persistencePerspective); Entity[] entities = helper.getRecords(indexFieldMetadata, indexFields); // We need to get the total number of records available because the entityList returned may not be the full set. Map<String, FieldMetadata> originalProps = helper.getSimpleMergedProperties(IndexField.class.getName(), persistencePerspective); List<FilterMapping> filterMappings = helper.getFilterMappings(persistencePerspective, cto, IndexField.class.getName(), originalProps); int totalRecords = helper.getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings); // Create a Dynamic Result Set from the entity list created above. DynamicResultSet resultSet = new DynamicResultSet(entities, (didFilter ? entities.length : totalRecords)); return resultSet; } DynamicResultSet resultSet = helper.getCompatibleModule(OperationType.BASIC).fetch(persistencePackage, cto); return resultSet; }