List of usage examples for javax.persistence.criteria CriteriaBuilder and
Predicate and(Predicate... restrictions);
From source file:cn.imethan.common.repository.DynamicSpecifications.java
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz) { return new Specification<T>() { @Override//w ww . j ava2 s . co m public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (filters != null && !filters.isEmpty()) { List<Predicate> predicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, Task??"user.name"filedName, ?Task.user.name String[] names = StringUtils.split(filter.fieldName, "."); Path expression = root.get(names[0]); try { for (int i = 1; i < names.length; i++) { expression = expression.get(names[i]); } } catch (Exception e) { e.printStackTrace(); } // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case IN: In in = builder.in(expression); String[] valueStrings = StringUtils.split(filter.value.toString(), ","); List<Long> list = new ArrayList<Long>(); for (String value : valueStrings) { list.add(Long.valueOf(value.trim())); } in.value(list); predicates.add(in); break; case NOTIN: In in1 = builder.in(expression); String[] valueStrings1 = StringUtils.split(filter.value.toString(), ","); List<Long> list1 = new ArrayList<Long>(); for (String value : valueStrings1) { list1.add(Long.valueOf(value.trim())); } in1.value(list1); predicates.add(builder.not(in1)); break; } } // ? and ??? if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } } // //hibernate // //org.hibernate.ejb.criteria.CriteriaQueryImpl // if(query instanceof org.hibernate.ejb.QueryImpl) { // @SuppressWarnings("rawtypes") // org.hibernate.ejb.QueryImpl hibernateQuery = (org.hibernate.ejb.QueryImpl)query; // org.hibernate.Query hQuery = hibernateQuery.getHibernateQuery(); // hQuery.setCacheable(true); // } return builder.conjunction(); } }; }
From source file:com.netflix.genie.web.data.repositories.jpa.specifications.JpaJobSpecs.java
/** * Generate a criteria query predicate for a where clause based on the given parameters. * * @param root The root to use * @param cb The criteria builder to use * @param id The job id/* w ww . j ava 2 s .c om*/ * @param name The job name * @param user The user who created the job * @param statuses The job statuses * @param tags The tags for the jobs to find * @param clusterName The cluster name * @param cluster The cluster the job should have been run on * @param commandName The command name * @param command The command the job should have been run with * @param minStarted The time which the job had to start after in order to be return (inclusive) * @param maxStarted The time which the job had to start before in order to be returned (exclusive) * @param minFinished The time which the job had to finish after in order to be return (inclusive) * @param maxFinished The time which the job had to finish before in order to be returned (exclusive) * @param grouping The job grouping to search for * @param groupingInstance The job grouping instance to search for * @return The specification */ @SuppressWarnings("checkstyle:parameternumber") public static Predicate getFindPredicate(final Root<JobEntity> root, final CriteriaBuilder cb, @Nullable final String id, @Nullable final String name, @Nullable final String user, @Nullable final Set<JobStatus> statuses, @Nullable final Set<String> tags, @Nullable final String clusterName, @Nullable final ClusterEntity cluster, @Nullable final String commandName, @Nullable final CommandEntity command, @Nullable final Instant minStarted, @Nullable final Instant maxStarted, @Nullable final Instant minFinished, @Nullable final Instant maxFinished, @Nullable final String grouping, @Nullable final String groupingInstance) { final List<Predicate> predicates = new ArrayList<>(); if (StringUtils.isNotBlank(id)) { predicates.add( JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.uniqueId), id)); } if (StringUtils.isNotBlank(name)) { predicates .add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.name), name)); } if (StringUtils.isNotBlank(user)) { predicates .add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.user), user)); } if (statuses != null && !statuses.isEmpty()) { final List<Predicate> orPredicates = statuses.stream() .map(status -> cb.equal(root.get(JobEntity_.status), status)).collect(Collectors.toList()); predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()]))); } if (tags != null && !tags.isEmpty()) { predicates.add( cb.like(root.get(JobEntity_.tagSearchString), JpaSpecificationUtils.getTagLikeString(tags))); } if (cluster != null) { predicates.add(cb.equal(root.get(JobEntity_.cluster), cluster)); } if (StringUtils.isNotBlank(clusterName)) { predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.clusterName), clusterName)); } if (command != null) { predicates.add(cb.equal(root.get(JobEntity_.command), command)); } if (StringUtils.isNotBlank(commandName)) { predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.commandName), commandName)); } if (minStarted != null) { predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.started), minStarted)); } if (maxStarted != null) { predicates.add(cb.lessThan(root.get(JobEntity_.started), maxStarted)); } if (minFinished != null) { predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.finished), minFinished)); } if (maxFinished != null) { predicates.add(cb.lessThan(root.get(JobEntity_.finished), maxFinished)); } if (grouping != null) { predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.grouping), grouping)); } if (groupingInstance != null) { predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.groupingInstance), groupingInstance)); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }
From source file:me.ineson.demo.service.utils.RestUtils.java
/** * @param where/* www.j a v a2s . c o m*/ * @param root * @param query * @param builder * @param translations * @return */ public static Predicate parseWhereClause(String where, Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder, Map<String, String> translations) { List<Predicate> predicates = new ArrayList<Predicate>(); for (String singleCriteria : new StrTokenizer(where, ",").getTokenList()) { if (StringUtils.isNotBlank(singleCriteria)) { int equalsIndex = singleCriteria.indexOf("="); if (equalsIndex > 0) { String fieldPath = singleCriteria.substring(0, equalsIndex); String value = singleCriteria.substring(equalsIndex + 1); if (translations != null && translations.containsKey(fieldPath)) { String newFieldPath = translations.get(fieldPath); log.debug("replacing field {} with {} ", fieldPath, newFieldPath); fieldPath = newFieldPath; } StrTokenizer tokenizer = new StrTokenizer(fieldPath, "."); javax.persistence.criteria.Path<?> expression = null; while (tokenizer.hasNext()) { String field = tokenizer.next(); if (tokenizer.hasNext()) { if (expression == null) { expression = root.join(field); } else { // expression = expression.join( field); throw new IllegalArgumentException( "Paths to joins of greater than a depth of 1 are not implemented yet"); } } else { if (expression == null) { log.info("expression0 {}", expression); expression = root.get(field); log.info("expression1 {}", expression); } else { expression = expression.get(field); } } } Object realValue = value; if ("bodyType".equals(fieldPath)) { me.ineson.demo.service.SolarBodyType solarBodyType = me.ineson.demo.service.SolarBodyType .valueOf(value); switch (solarBodyType) { case PLANET: realValue = SolarBodyType.Planet; break; case SUN: realValue = SolarBodyType.Sun; break; case DWARF_PLANET: realValue = SolarBodyType.DwarfPlanet; break; default: realValue = solarBodyType; } log.info("enum bodyType before {} after {}", value, realValue); } log.info("expression9 {}", expression); predicates.add(builder.equal(expression, realValue)); } } } log.debug("predictes "); if (predicates.size() == 0) { return null; } if (predicates.size() == 1) { return predicates.get(0); } return builder.and(predicates.toArray(new Predicate[predicates.size()])); }
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);//from w w w . j a v a2 s.c o m } 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
public IBundleProvider search(final SearchParameterMap theParams) { myParams = theParams;/*from w ww . j a v a2 s .co m*/ StopWatch w = new StopWatch(); doInitializeSearch(); DateRangeParam lu = theParams.getLastUpdated(); // Collection<Long> loadPids; if (theParams.getEverythingMode() != null) { Long pid = null; if (theParams.get(BaseResource.SP_RES_ID) != null) { StringParam idParm = (StringParam) theParams.get(BaseResource.SP_RES_ID).get(0).get(0); pid = BaseHapiFhirDao.translateForcedIdToPid(myResourceName, idParm.getValue(), myForcedIdDao); } if (theParams.containsKey(Constants.PARAM_CONTENT) || theParams.containsKey(Constants.PARAM_TEXT)) { List<Long> pids = mySearchDao.everything(myResourceName, theParams); if (pids.isEmpty()) { return doReturnProvider(); } doSetPids(pids); } else { CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> cq = builder.createTupleQuery(); Root<ResourceTable> from = cq.from(ResourceTable.class); List<Predicate> predicates = new ArrayList<Predicate>(); if (pid != null) { predicates.add(builder.equal(from.get("myId"), pid)); } predicates.add(builder.equal(from.get("myResourceType"), myResourceName)); predicates.add(builder.isNull(from.get("myDeleted"))); cq.where(builder.and(SearchBuilder.toArray(predicates))); Join<Object, Object> join = from.join("myIncomingResourceLinks", JoinType.LEFT); cq.multiselect(from.get("myId").as(Long.class), join.get("mySourceResourcePid").as(Long.class)); TypedQuery<Tuple> query = myEntityManager.createQuery(cq); Set<Long> pids = new HashSet<Long>(); for (Tuple next : query.getResultList()) { pids.add(next.get(0, Long.class)); Long nextLong = next.get(1, Long.class); if (nextLong != null) { pids.add(nextLong); } } doSetPids(pids); } } else if (theParams.isEmpty()) { TypedQuery<Long> query = createSearchAllByTypeQuery(lu); doSetPids(query.getResultList()); } else { if (mySearchDao == null) { if (theParams.containsKey(Constants.PARAM_TEXT)) { throw new InvalidRequestException( "Fulltext search is not enabled on this service, can not process parameter: " + Constants.PARAM_TEXT); } else if (theParams.containsKey(Constants.PARAM_CONTENT)) { throw new InvalidRequestException( "Fulltext search is not enabled on this service, can not process parameter: " + Constants.PARAM_CONTENT); } } else { List<Long> searchResultPids = mySearchDao.search(myResourceName, theParams); if (searchResultPids != null) { if (searchResultPids.isEmpty()) { return doReturnProvider(); } doSetPids(searchResultPids); } } if (!theParams.isEmpty()) { searchForIdsWithAndOr(theParams, lu); } } // // Load _include and _revinclude before filter and sort in everything mode // if (theParams.getEverythingMode() != null) { // if (theParams.getRevIncludes() != null && theParams.getRevIncludes().isEmpty() == false) { // loadPids.addAll(loadReverseIncludes(loadPids, theParams.getRevIncludes(), true, // theParams.getEverythingMode())); // loadPids.addAll(loadReverseIncludes(loadPids, theParams.getIncludes(), false, theParams.getEverythingMode())); // } // } if (doHaveNoResults()) { return doReturnProvider(); } // Handle _lastUpdated if (lu != null) { filterResourceIdsByLastUpdated(lu); if (doHaveNoResults()) { return doReturnProvider(); } } // Handle sorting if any was provided processSort(theParams); ourLog.info(" {} on {} in {}ms", new Object[] { myResourceName, theParams, w.getMillisAndRestart() }); return doReturnProvider(); }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateParamMissingResourceLink(String joinName, String theParamName) { CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceTable> from = cq.from(ResourceTable.class); cq.select(from.get("myId").as(Long.class)); Subquery<Long> subQ = cq.subquery(Long.class); Root<ResourceLink> subQfrom = subQ.from(ResourceLink.class); subQ.select(subQfrom.get("mySourceResourcePid").as(Long.class)); // subQ.where(builder.equal(subQfrom.get("myParamName"), theParamName)); Predicate path = createResourceLinkPathPredicate(theParamName, subQfrom); subQ.where(path);//from w w w. j a va 2 s . co m List<Predicate> predicates = new ArrayList<Predicate>(); createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class)); predicates.add(builder.not(builder.in(from.get("myId")).value(subQ))); predicates.add(builder.equal(from.get("myResourceType"), myResourceName)); cq.where(builder.and(toArray(predicates))); TypedQuery<Long> q = myEntityManager.createQuery(cq); List<Long> resultList = q.getResultList(); doSetPids(new HashSet<Long>(resultList)); }
From source file:com.ims.service.ProductStockInfoService.java
public List<ProductStockInfo> findProdStockInfoListFrom(final ProdStockSearchCriteria stockSearchCriteria) { Specification<ProductStockInfo> speci = new Specification<ProductStockInfo>() { @Override//from ww w .j a v a 2s . 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:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java
private List<HmFolder> findRootFolders() { Specification<HmFolder> spec = new Specification<HmFolder>() { @Override// w w w .ja v a2s .c o m public Predicate toPredicate(Root<HmFolder> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate[] predicates = new Predicate[1]; predicates[0] = cb.isNull(root.get("parent")); return cb.and(predicates); } }; return rep.findAll(spec); }
From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java
private List<HmFolder> findChildNodes(final Long parentId) { Specification<HmFolder> spec = new Specification<HmFolder>() { @Override/*w w w . java 2 s. com*/ public Predicate toPredicate(Root<HmFolder> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate[] predicates = new Predicate[1]; predicates[0] = cb.equal(root.get("parent"), parentId); return cb.and(predicates); } }; return rep.findAll(spec); }
From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java
private long findChildNodeCount(final Long parentId) { Specification<HmFolder> spec = new Specification<HmFolder>() { @Override/* www. j a v a 2 s .c o m*/ public Predicate toPredicate(Root<HmFolder> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate[] predicates = new Predicate[1]; predicates[0] = cb.equal(root.get("parent"), parentId); return cb.and(predicates); } }; return rep.count(spec); }