List of usage examples for javax.persistence.criteria CriteriaBuilder desc
Order desc(Expression<?> x);
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * suche eines Bentzers//from ww w . j a v a2 s . co m * * @param user_level * @param searchstring * @param max * @param start * @return */ public List<Users> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start, String orderby, boolean asc) { if (authLevelManagement.checkAdminLevel(user_level)) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Users> cq = cb.createQuery(Users.class); Root<Users> c = cq.from(Users.class); Expression<String> literal = cb.literal("%" + searchstring + "%"); // crit.add(Restrictions.ilike(searchcriteria, "%" + // 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<Users> q = em.createQuery(cq); q.setFirstResult(start); q.setMaxResults(max); List<Users> contactsZ = q.getResultList(); return contactsZ; } catch (Exception ex2) { log.error("searchUser", ex2); } } return null; }
From source file:com.deloitte.smt.service.SignalDetectionService.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public SmtResponse findAllForSearch(SearchDto searchDto) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(); Root<SignalDetection> rootSignalDetection = criteriaQuery.from(SignalDetection.class); Join<SignalDetection, TopicSignalDetectionAssignmentAssignees> joinDetectionAssignees = rootSignalDetection .join("topicSignalDetectionAssignmentAssignees", JoinType.LEFT); //left outer join if (null != searchDto) { Root<Ingredient> rootIngredient = criteriaQuery.from(Ingredient.class); List<Predicate> predicates = new ArrayList<>(10); predicates.add(criteriaBuilder.equal(rootSignalDetection.get("id"), rootIngredient.get(SmtConstant.DETECTION_ID.getDescription()))); addDescription(searchDto, criteriaBuilder, rootSignalDetection, predicates); addFrequency(searchDto, criteriaBuilder, rootSignalDetection, predicates); addIngredients(searchDto, criteriaBuilder, rootIngredient, predicates); addProducts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addLicenses(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addSocs(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addHlts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addHlgts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addPts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addCreatedOrLastRunDate(searchDto, criteriaBuilder, rootSignalDetection, predicates); /**TopicSignalValidationAssignmentAssignees **/ addUserGroupKeys(searchDto, criteriaBuilder, joinDetectionAssignees, rootSignalDetection, predicates); Predicate andPredicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); criteriaQuery.multiselect(rootSignalDetection).where(andPredicate) .orderBy(criteriaBuilder .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription()))) .distinct(true);/* ww w . jav a2s.c om*/ } else { criteriaQuery.multiselect(rootSignalDetection) .orderBy(criteriaBuilder .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription()))) .distinct(true); } SmtResponse smtResponse = new SmtResponse(); TypedQuery<SignalDetection> q = entityManager.createQuery(criteriaQuery); if (!CollectionUtils.isEmpty(q.getResultList())) { smtResponse.setTotalRecords(q.getResultList().size()); } if (searchDto != null && searchDto.getFetchSize() != 0) { q.setFirstResult(searchDto.getFromRecord()); q.setMaxResults(searchDto.getFetchSize()); smtResponse.setFetchSize(searchDto.getFetchSize()); smtResponse.setFromRecord(searchDto.getFromRecord()); } smtResponse.setResult(q.getResultList()); if (!CollectionUtils.isEmpty(smtResponse.getResult())) { List<SignalDetection> result = (List<SignalDetection>) smtResponse.getResult(); for (SignalDetection signalDetection : result) { signalDetection.setDenominatorForPoisson( denominatorForPoissonRepository.findByDetectionId(signalDetection.getId())); } } return smtResponse; }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void createSort(CriteriaBuilder theBuilder, Root<ResourceTable> theFrom, SortSpec theSort, List<Order> theOrders, List<Predicate> thePredicates) { if (theSort == null || isBlank(theSort.getParamName())) { return;//ww w . j a va2 s. c o m } if (BaseResource.SP_RES_ID.equals(theSort.getParamName())) { From<?, ?> forcedIdJoin = theFrom.join("myForcedId", JoinType.LEFT); if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) { theOrders.add(theBuilder.asc(forcedIdJoin.get("myForcedId"))); theOrders.add(theBuilder.asc(theFrom.get("myId"))); } else { theOrders.add(theBuilder.desc(forcedIdJoin.get("myForcedId"))); theOrders.add(theBuilder.desc(theFrom.get("myId"))); } createSort(theBuilder, theFrom, theSort.getChain(), theOrders, thePredicates); return; } if (Constants.PARAM_LASTUPDATED.equals(theSort.getParamName())) { if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) { theOrders.add(theBuilder.asc(theFrom.get("myUpdated"))); } else { theOrders.add(theBuilder.desc(theFrom.get("myUpdated"))); } createSort(theBuilder, theFrom, theSort.getChain(), theOrders, thePredicates); return; } RuntimeSearchParam param = getSearchParam(theSort.getParamName()); if (param == null) { throw new InvalidRequestException("Unknown sort parameter '" + theSort.getParamName() + "'"); } String joinAttrName; String[] sortAttrName; switch (param.getParamType()) { case STRING: joinAttrName = "myParamsString"; sortAttrName = new String[] { "myValueExact" }; break; case DATE: joinAttrName = "myParamsDate"; sortAttrName = new String[] { "myValueLow" }; break; case REFERENCE: joinAttrName = "myResourceLinks"; sortAttrName = new String[] { "myTargetResourcePid" }; break; case TOKEN: joinAttrName = "myParamsToken"; sortAttrName = new String[] { "mySystem", "myValue" }; break; case NUMBER: joinAttrName = "myParamsNumber"; sortAttrName = new String[] { "myValue" }; break; case URI: joinAttrName = "myParamsUri"; sortAttrName = new String[] { "myUri" }; break; case QUANTITY: joinAttrName = "myParamsQuantity"; sortAttrName = new String[] { "myValue" }; break; default: throw new InvalidRequestException("This server does not support _sort specifications of type " + param.getParamType() + " - Can't serve _sort=" + theSort.getParamName()); } From<?, ?> stringJoin = theFrom.join(joinAttrName, JoinType.INNER); if (param.getParamType() == RestSearchParameterTypeEnum.REFERENCE) { thePredicates.add(stringJoin.get("mySourcePath").as(String.class).in(param.getPathsSplit())); } else { thePredicates.add(theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName())); } // Predicate p = theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName()); // Predicate pn = theBuilder.isNull(stringJoin.get("myParamName")); // thePredicates.add(theBuilder.or(p, pn)); for (String next : sortAttrName) { if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) { theOrders.add(theBuilder.asc(stringJoin.get(next))); } else { theOrders.add(theBuilder.desc(stringJoin.get(next))); } } createSort(theBuilder, theFrom, theSort.getChain(), theOrders, thePredicates); }
From source file:com.ims.service.ProductStockInfoService.java
public List<ProductStockInfo> findProdStockInfoListFrom(final ProdStockSearchCriteria stockSearchCriteria) { Specification<ProductStockInfo> speci = new Specification<ProductStockInfo>() { @Override// w w w.jav a2 s.c o m public Predicate toPredicate(Root<ProductStockInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(cb.equal(root.get("stockType"), stockSearchCriteria.getStockType())); if (StringUtils.isNotEmpty(stockSearchCriteria.getProdCategoryCode())) { predicates.add(cb.equal(root.get("categoryCode"), stockSearchCriteria.getProdCategoryCode())); } if (StringUtils.isNotEmpty(stockSearchCriteria.getProdCode())) { predicates.add(cb.like(root.<String>get("productCode"), "%" + stockSearchCriteria.getProdCode() + "%")); } String compareCode = stockSearchCriteria.getCompareCode(); if (StringUtils.isNotEmpty(compareCode) && stockSearchCriteria.isIncludeComparedValue()) { Path<ProductAmount> productAmount = root.<ProductAmount>get("productAmount"); if (CompareCode.isEqual(compareCode)) { predicates.add( cb.equal(productAmount.get("totalAmount"), stockSearchCriteria.getStockAmount())); } else if (CompareCode.isGreater(compareCode)) { predicates.add(cb.greaterThan(productAmount.<Integer>get("totalAmount"), stockSearchCriteria.getStockAmount())); } else if (CompareCode.isLess(compareCode)) { predicates.add(cb.lessThan(productAmount.<Integer>get("totalAmount"), stockSearchCriteria.getStockAmount())); } else if (CompareCode.isGreaterOrEqual(compareCode)) { predicates.add(cb.greaterThanOrEqualTo(productAmount.<Integer>get("totalAmount"), stockSearchCriteria.getStockAmount())); } else if (CompareCode.isLessOrEqual(compareCode)) { predicates.add(cb.lessThanOrEqualTo(productAmount.<Integer>get("totalAmount"), stockSearchCriteria.getStockAmount())); } else if (CompareCode.isEqualAlertAmount(compareCode)) { predicates.add(cb.equal(productAmount.get("totalAmount"), root.get("alertStockAmount"))); } else if (CompareCode.isGreaterThanAlertAmount(compareCode)) { predicates.add(cb.greaterThan(productAmount.<String>get("totalAmount"), root.<String>get("alertStockAmount"))); } else if (CompareCode.isLessThanAlertAmount(compareCode)) { predicates.add(cb.lessThan(productAmount.<String>get("totalAmount"), root.<String>get("alertStockAmount"))); } if (stockSearchCriteria.isTransformAction() && ((CompareCode.isLess(compareCode) || CompareCode.isLessOrEqual(compareCode)))) { predicates.add(cb.greaterThan(productAmount.<Integer>get("totalAmount"), 0)); } } query.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))) .orderBy(cb.desc(root.get("categoryCode")), cb.asc(root.get("productCode"))); return null; } }; return productStockInfoRepository.findAll(speci); }
From source file:com.yunguchang.data.ApplicationRepository.java
public List<TBusApplyinfoEntity> getAllApplications(String coordinatorUserId, String reasonType, String status, DateTime startBefore, DateTime startAfter, DateTime endBefore, DateTime endAfter, Integer offset, Integer limit, OrderByParam orderByParam, PrincipalExt principalExt) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class); Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class); applyRoot.fetch(TBusApplyinfoEntity_.passenger); Fetch<TBusApplyinfoEntity, TSysUserEntity> fetchCoordinator = applyRoot .fetch(TBusApplyinfoEntity_.coordinator); applyRoot.fetch(TBusApplyinfoEntity_.department); Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT); scheduleFetch.fetch(TBusScheduleRelaEntity_.senduser, JoinType.LEFT); scheduleFetch.fetch(TBusScheduleRelaEntity_.reciveuser, JoinType.LEFT); Fetch<TBusScheduleRelaEntity, TBusScheduleCarEntity> fetchScheduleCar = scheduleFetch .fetch(TBusScheduleRelaEntity_.scheduleCars, JoinType.LEFT); fetchScheduleCar.fetch(TBusScheduleCarEntity_.car, JoinType.LEFT).fetch(TAzCarinfoEntity_.depot, JoinType.LEFT);//from ww w . j av a 2s. co m fetchScheduleCar.fetch(TBusScheduleCarEntity_.driver, JoinType.LEFT).fetch(TRsDriverinfoEntity_.department, JoinType.LEFT); Predicate predicate = cb.conjunction(); if (coordinatorUserId != null) { Join<TBusApplyinfoEntity, TSysUserEntity> joinCoordinator = (Join<TBusApplyinfoEntity, TSysUserEntity>) fetchCoordinator; predicate = cb.and(predicate, cb.equal(joinCoordinator.get(TSysUserEntity_.userid), coordinatorUserId)); } if (reasonType != null) { predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.reason), reasonType)); } if (status != null) { if (status.indexOf(":") < 0) { predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.status), status)); } else { String[] statusList = status.split(":"); predicate = cb.and(predicate, applyRoot.get(TBusApplyinfoEntity_.status).in(Arrays.asList(statusList))); } } if (startBefore != null) { predicate = cb.and(predicate, cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startBefore)); } if (startAfter != null) { predicate = cb.and(predicate, cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startAfter)); } if (endBefore != null) { predicate = cb.and(predicate, cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endBefore)); } if (endAfter != null) { predicate = cb.and(predicate, cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endAfter)); } cq.where(predicate); List<Order> orders = new ArrayList<>(); if (orderByParam != null) { for (OrderByParam.OrderBy orderBy : orderByParam.getOrderBies()) { Order order = null; if (orderBy.getFiled().toLowerCase().equals("start".toLowerCase())) { order = cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime)); } if (order != null && !orderBy.isAsc()) { order = order.reverse(); } if (order != null) { orders.add(order); } } } if (orders.size() == 0) { cq.orderBy(cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime))); } else { cq.orderBy(orders); } TypedQuery<TBusApplyinfoEntity> query = em.createQuery(cq); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } applySecurityFilter("applications", principalExt); return query.getResultList(); }
From source file:org.apache.ambari.server.api.query.JpaSortBuilder.java
/** * Builds the list of sort orders based on the supplied request and JPA * predicate visitor.// w w w .ja v a2 s . c o m * * @param sortRequests * the Ambari sort request properties to turn into a JPA sort * request. If {@code null} or the {@link SortRequestProperty} list * is null, an empty list is returned. * @param visitor * a visitor that knows how to convert the Ambari properties into * {@link SingularAttribute} (not {@code null}). * @return a list of sorts or an empty list if none (never {@code null}). */ public List<Order> buildSortOrders(SortRequest sortRequest, JpaPredicateVisitor<T> visitor) { if (null == sortRequest || null == sortRequest.getProperties()) { return Collections.emptyList(); } CriteriaBuilder builder = visitor.getCriteriaBuilder(); List<SortRequestProperty> sortProperties = sortRequest.getProperties(); List<Order> sortOrders = new ArrayList<Order>(sortProperties.size()); for (SortRequestProperty sort : sortProperties) { String propertyId = sort.getPropertyId(); List<? extends SingularAttribute<?, ?>> singularAttributes = visitor.getPredicateMapping(propertyId); if (null == singularAttributes || singularAttributes.size() == 0) { continue; } Path<?> path = null; for (SingularAttribute<?, ?> singularAttribute : singularAttributes) { if (null == path) { CriteriaQuery<T> query = visitor.getCriteriaQuery(); Set<Root<?>> roots = query.getRoots(); // if there are existing roots; use the existing roots to prevent more // roots from being added potentially causing a cartesian product // where we don't want one if (null != roots && !roots.isEmpty()) { Iterator<Root<?>> iterator = roots.iterator(); while (iterator.hasNext()) { Root<?> root = iterator.next(); Class<?> visitorEntityClass = visitor.getEntityClass(); if (ObjectUtils.equals(visitorEntityClass, root.getJavaType()) || ObjectUtils.equals(visitorEntityClass, root.getModel().getJavaType())) { path = root.get(singularAttribute.getName()); break; } } } // no roots exist already which match this entity class, create a new // path if (null == path) { path = query.from(visitor.getEntityClass()).get(singularAttribute.getName()); } } else { path = path.get(singularAttribute.getName()); } } Order sortOrder = null; if (sort.getOrder() == org.apache.ambari.server.controller.spi.SortRequest.Order.ASC) { sortOrder = builder.asc(path); } else { sortOrder = builder.desc(path); } sortOrders.add(sortOrder); } return sortOrders; }
From source file:org.apache.openmeetings.data.user.UserManager.java
/** * query for a list of users//ww w. j a va 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// ww w . j av a2 s .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);// www .ja v a 2 s . c o m 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.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"); }//w w w.j ava 2s . 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 (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); }