List of usage examples for javax.persistence.criteria CriteriaBuilder asc
Order asc(Expression<?> x);
From source file:eu.domibus.common.dao.ErrorLogDao.java
public List<ErrorLogEntry> findPaged(int from, int max, String column, boolean asc, HashMap<String, Object> filters) { CriteriaBuilder cb = this.em.getCriteriaBuilder(); CriteriaQuery<ErrorLogEntry> cq = cb.createQuery(ErrorLogEntry.class); Root<ErrorLogEntry> ele = cq.from(ErrorLogEntry.class); cq.select(ele);/*ww w . j a va 2 s. c o m*/ List<Predicate> predicates = new ArrayList<Predicate>(); for (Map.Entry<String, Object> filter : filters.entrySet()) { if (filter.getValue() != null) { if (filter.getValue() instanceof String) { if (!filter.getValue().toString().isEmpty()) { switch (filter.getKey().toString()) { case "": break; case "timestampFrom": predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("timestamp"), Timestamp.valueOf(filter.getValue().toString()))); break; case "timestampTo": predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("timestamp"), Timestamp.valueOf(filter.getValue().toString()))); break; case "notifiedFrom": predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("notified"), Timestamp.valueOf(filter.getValue().toString()))); break; case "notifiedTo": predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("notified"), Timestamp.valueOf(filter.getValue().toString()))); break; default: predicates.add(cb.like(ele.<String>get(filter.getKey()), (String) filter.getValue())); break; } } } else { predicates.add(cb.equal(ele.<String>get(filter.getKey()), filter.getValue())); } } } cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); if (column != null) { if (asc) { cq.orderBy(cb.asc(ele.get(column))); } else { cq.orderBy(cb.desc(ele.get(column))); } } final TypedQuery<ErrorLogEntry> query = this.em.createQuery(cq); query.setFirstResult(from); query.setMaxResults(max); return query.getResultList(); }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
private void createSort(CriteriaBuilder theBuilder, Root<ResourceTable> theFrom, SortSpec theSort, List<Order> theOrders, List<Predicate> thePredicates) { if (theSort == null || isBlank(theSort.getParamName())) { return;//w w w . j a va 2 s . c o m } if ("_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, null); return; } RuntimeResourceDefinition resourceDef = getContext().getResourceDefinition(myResourceType); RuntimeSearchParam param = resourceDef.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 = "myValueExact"; break; case DATE: joinAttrName = "myParamsDate"; sortAttrName = "myValueLow"; break; default: throw new NotImplementedException("This server does not support _sort specifications of type " + param.getParamType() + " - Can't serve _sort=" + theSort.getParamName()); } From<?, ?> stringJoin = theFrom.join(joinAttrName, JoinType.INNER); // Predicate p = theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName()); // Predicate pn = theBuilder.isNull(stringJoin.get("myParamName")); // thePredicates.add(theBuilder.or(p, pn)); if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) { theOrders.add(theBuilder.asc(stringJoin.get(sortAttrName))); } else { theOrders.add(theBuilder.desc(stringJoin.get(sortAttrName))); } createSort(theBuilder, theFrom, theSort.getChain(), theOrders, null); }
From source file:com.yunguchang.data.ApplicationRepository.java
public List<TAzCarinfoEntity> listAllCandidateCars(String[] applicationIds, String keyword, Integer offset, Integer limit, PrincipalExt principalExt) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TAzCarinfoEntity> cq = cb.createQuery(TAzCarinfoEntity.class); Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class); carRoot.fetch(TAzCarinfoEntity_.driver, JoinType.LEFT); cq.select(carRoot);//from w ww . java 2 s . c o m Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class); applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, null, cb, principalExt); Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.clzt), "02"), cb.or(cb.equal(carRoot.get(TAzCarinfoEntity_.repairingState), RepairingState.NONE.id()), cb.isNull(carRoot.get(TAzCarinfoEntity_.repairingState)) ), cb.not(cb.exists(overlapScheduleCarSubQuery)) ); if (keyword != null) { predicate = cb.and(predicate, cb.or(cb.like(carRoot.get(TAzCarinfoEntity_.sysOrg).get(TSysOrgEntity_.orgname), "%" + keyword + "%"), cb.like(carRoot.get(TAzCarinfoEntity_.cphm), "%" + keyword + "%"))); } cq.where(predicate); cq.orderBy(cb.asc(carRoot.get(TAzCarinfoEntity_.cphm))); TypedQuery<TAzCarinfoEntity> query = em.createQuery(cq); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } applySecurityFilter("cars", principalExt); return query.getResultList(); }
From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java
/** * list entity by CriteriaInfo//from ww w .java 2 s . c o m * * @param criteriaInfo * @return PagedResult */ public PagedResult<T> list(CriteriaInfo criteriaInfo) { EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(entityClass); Root<T> userRoot = cq.from(entityClass); cq.select(userRoot); ParamInfo paramInfo = criteriaInfo.getParamInfo(); PageInfo pageInfo = criteriaInfo.getPageInfo(); SortInfo sortInfo = criteriaInfo.getSortInfo(); //build query for paramInfo if (paramInfo != null) { Set<Predicate> andCriteria = new HashSet(); Set<Predicate> orCriteria = new HashSet(); for (ParamItem item : paramInfo.getParamItems()) { Predicate predicate; if (item.getValue() instanceof String) { //fuzy search for string String regExp = "%" + item.getValue() + "%"; predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp); } else { predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue()); } switch (item.getOperator()) { case AND: andCriteria.add(predicate); break; case OR: orCriteria.add(predicate); break; } } if (orCriteria.size() > 0) { Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()])); andCriteria.add(or); } if (andCriteria.size() > 0) { Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()])); cq.where(and); } } //build query for sortInfo Set<Order> orderPredicate = new HashSet<>(); if (sortInfo != null) { for (SortItem item : sortInfo.getSortItems()) { if (item.isDescending()) { orderPredicate.add(cb.desc(userRoot.get(item.getFieldName()))); } else { orderPredicate.add(cb.asc(userRoot.get(item.getFieldName()))); } } } if (orderPredicate.size() > 0) { cq.orderBy(orderPredicate.toArray(new Order[orderPredicate.size()])); } TypedQuery<T> query = em.createQuery(cq); //set result range if (pageInfo != null) { query.setFirstResult(pageInfo.getOffset()); query.setMaxResults(pageInfo.getSize()); } int totalSize; if (paramInfo != null && paramInfo.getParamItems().size() > 0) { totalSize = count(paramInfo); } else { totalSize = count(); } return new PagedResult(query.getResultList(), totalSize); }
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * suche eines Bentzers/*from w w w .j a v a2 s . c o 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: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;/*from w ww.j a v a2 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.yunguchang.data.ApplicationRepository.java
public List<TRsDriverinfoEntity> listAllCandidateDrivers(String[] applicationIds, String carId, String keyword, Integer offset, Integer limit, PrincipalExt principalExt) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TRsDriverinfoEntity> cq = cb.createQuery(TRsDriverinfoEntity.class); Root<TRsDriverinfoEntity> driverRoot = cq.from(TRsDriverinfoEntity.class); Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class); cq.select(driverRoot);//from ww w.jav a 2 s . com Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class); applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, driverRoot, cb, principalExt); Subquery<TRsDriverinfoEntity> subqueryLicense = cq.subquery(TRsDriverinfoEntity.class); Root<TAzJzRelaEntity> licenseMapping = subqueryLicense.from(TAzJzRelaEntity.class); subqueryLicense.select(driverRoot); subqueryLicense.where( cb.equal(carRoot.get(TAzCarinfoEntity_.xszcx), licenseMapping.get(TAzJzRelaEntity_.xszcx)), cb.equal(licenseMapping.get(TAzJzRelaEntity_.jzyq), driverRoot.get(TRsDriverinfoEntity_.drivecartype))); Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.id), carId), cb.equal(driverRoot.get(TRsDriverinfoEntity_.department), carRoot.get(TAzCarinfoEntity_.sysOrg)), cb.equal(driverRoot.get(TRsDriverinfoEntity_.enabled), "1"), cb.or(cb.exists(subqueryLicense), cb.isNull(driverRoot.get(TRsDriverinfoEntity_.drivecartype)) ), cb.not(cb.exists(overlapScheduleCarSubQuery)) ); if (keyword != null) { predicate = cb.and(predicate, cb.or(cb.like(driverRoot.get(TRsDriverinfoEntity_.drivername), "%" + keyword + "%"))); } cq.where(predicate); cq.orderBy(cb .asc(cb.function("casttogbk", String.class, cb.trim(driverRoot.get(TRsDriverinfoEntity_.drivername)) ))); TypedQuery<TRsDriverinfoEntity> query = em.createQuery(cq); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } return query.getResultList(); }
From source file:com.ims.service.ProductStockInfoService.java
public List<ProductStockInfo> findProdStockInfoListFrom(final ProdStockSearchCriteria stockSearchCriteria) { Specification<ProductStockInfo> speci = new Specification<ProductStockInfo>() { @Override/* w ww.j a v a 2 s. c om*/ 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:org.apache.ambari.server.api.query.JpaSortBuilder.java
/** * Builds the list of sort orders based on the supplied request and JPA * predicate visitor./*from ww w . j a va2 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 v a 2s . 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; }