List of usage examples for javax.persistence.criteria CriteriaBuilder or
Predicate or(Predicate... restrictions);
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
private Set<Long> addPredicateQuantity(String theParamName, Set<Long> thePids, List<? extends IQueryParameterType> theList) { if (theList == null || theList.isEmpty()) { return thePids; }/*from w w w . j av a2 s . co m*/ CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceIndexedSearchParamQuantity> from = cq.from(ResourceIndexedSearchParamQuantity.class); cq.select(from.get("myResourcePid").as(Long.class)); List<Predicate> codePredicates = new ArrayList<Predicate>(); for (IQueryParameterType nextOr : theList) { IQueryParameterType params = nextOr; String systemValue; String unitsValue; QuantityCompararatorEnum cmpValue; BigDecimal valueValue; boolean approx = false; if (params instanceof BaseQuantityDt) { BaseQuantityDt param = (BaseQuantityDt) params; systemValue = param.getSystemElement().getValueAsString(); unitsValue = param.getUnitsElement().getValueAsString(); cmpValue = QuantityCompararatorEnum.VALUESET_BINDER .fromCodeString(param.getComparatorElement().getValueAsString()); valueValue = param.getValueElement().getValue(); } else if (params instanceof QuantityParam) { QuantityParam param = (QuantityParam) params; systemValue = param.getSystem().getValueAsString(); unitsValue = param.getUnits(); cmpValue = param.getComparator(); valueValue = param.getValue().getValue(); approx = param.isApproximate(); } else { throw new IllegalArgumentException("Invalid quantity type: " + params.getClass()); } Predicate system = null; if (!isBlank(systemValue)) { system = builder.equal(from.get("mySystem"), systemValue); } Predicate code = null; if (!isBlank(unitsValue)) { code = builder.equal(from.get("myUnits"), unitsValue); } Predicate num; if (cmpValue == null) { BigDecimal mul = approx ? new BigDecimal(0.1) : new BigDecimal(0.01); BigDecimal low = valueValue.subtract(valueValue.multiply(mul)); BigDecimal high = valueValue.add(valueValue.multiply(mul)); Predicate lowPred = builder.gt(from.get("myValue").as(BigDecimal.class), low); Predicate highPred = builder.lt(from.get("myValue").as(BigDecimal.class), high); num = builder.and(lowPred, highPred); } else { switch (cmpValue) { case GREATERTHAN: Expression<Number> path = from.get("myValue"); num = builder.gt(path, valueValue); break; case GREATERTHAN_OR_EQUALS: path = from.get("myValue"); num = builder.ge(path, valueValue); break; case LESSTHAN: path = from.get("myValue"); num = builder.lt(path, valueValue); break; case LESSTHAN_OR_EQUALS: path = from.get("myValue"); num = builder.le(path, valueValue); break; default: throw new IllegalStateException(cmpValue.getCode()); } } if (system == null && code == null) { codePredicates.add(num); } else if (system == null) { Predicate singleCode = builder.and(code, num); codePredicates.add(singleCode); } else if (code == null) { Predicate singleCode = builder.and(system, num); codePredicates.add(singleCode); } else { Predicate singleCode = builder.and(system, code, num); codePredicates.add(singleCode); } } Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0])); Predicate type = builder.equal(from.get("myResourceType"), myResourceName); Predicate name = builder.equal(from.get("myParamName"), theParamName); if (thePids.size() > 0) { Predicate inPids = (from.get("myResourcePid").in(thePids)); cq.where(builder.and(type, name, masterCodePredicate, inPids)); } else { cq.where(builder.and(type, name, masterCodePredicate)); } TypedQuery<Long> q = myEntityManager.createQuery(cq); return new HashSet<Long>(q.getResultList()); }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateReference(String theParamName, List<? extends IQueryParameterType> theList) { assert theParamName.contains(".") == false; if (Boolean.TRUE.equals(theList.get(0).getMissing())) { addPredicateParamMissingResourceLink("myResourceLinks", theParamName); return;/*from www.j ava2s. c o m*/ } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceLink> from = cq.from(ResourceLink.class); cq.select(from.get("mySourceResourcePid").as(Long.class)); List<Predicate> codePredicates = new ArrayList<Predicate>(); for (IQueryParameterType nextOr : theList) { IQueryParameterType params = nextOr; if (addPredicateMissingFalseIfPresentForResourceLink(builder, theParamName, from, codePredicates, nextOr)) { continue; } if (params instanceof ReferenceParam) { ReferenceParam ref = (ReferenceParam) params; if (isBlank(ref.getChain())) { IIdType dt = new IdDt(ref.getBaseUrl(), ref.getResourceType(), ref.getIdPart(), null); if (dt.hasBaseUrl()) { if (myCallingDao.getConfig().getTreatBaseUrlsAsLocal().contains(dt.getBaseUrl())) { dt = dt.toUnqualified(); } else { ourLog.debug("Searching for resource link with target URL: {}", dt.getValue()); Predicate eq = builder.equal(from.get("myTargetResourceUrl"), dt.getValue()); codePredicates.add(eq); continue; } } List<Long> targetPid; try { targetPid = myCallingDao.translateForcedIdToPids(dt); } catch (ResourceNotFoundException e) { doSetPids(new ArrayList<Long>()); return; } for (Long next : targetPid) { ourLog.debug("Searching for resource link with target PID: {}", next); Predicate eq = builder.equal(from.get("myTargetResourcePid"), next); codePredicates.add(eq); } } else { List<Class<? extends IBaseResource>> resourceTypes; String resourceId; if (!ref.getValue().matches("[a-zA-Z]+\\/.*")) { String paramPath = myContext.getResourceDefinition(myResourceType) .getSearchParam(theParamName).getPath(); if (paramPath.endsWith(".as(Reference)")) { paramPath = paramPath.substring(0, paramPath.length() - ".as(Reference)".length()) + "Reference"; } BaseRuntimeChildDefinition def = myContext.newTerser().getDefinition(myResourceType, paramPath); if (def instanceof RuntimeChildChoiceDefinition) { RuntimeChildChoiceDefinition choiceDef = (RuntimeChildChoiceDefinition) def; resourceTypes = choiceDef.getResourceTypes(); } else if (def instanceof RuntimeChildResourceDefinition) { RuntimeChildResourceDefinition resDef = (RuntimeChildResourceDefinition) def; resourceTypes = resDef.getResourceTypes(); } else { throw new ConfigurationException("Property " + paramPath + " of type " + myResourceName + " is not a resource: " + def.getClass()); } resourceId = ref.getValue(); } else { RuntimeResourceDefinition resDef = myContext.getResourceDefinition(ref.getResourceType()); resourceTypes = new ArrayList<Class<? extends IBaseResource>>(1); resourceTypes.add(resDef.getImplementingClass()); resourceId = ref.getIdPart(); } boolean foundChainMatch = false; String chain = ref.getChain(); String remainingChain = null; int chainDotIndex = chain.indexOf('.'); if (chainDotIndex != -1) { remainingChain = chain.substring(chainDotIndex + 1); chain = chain.substring(0, chainDotIndex); } for (Class<? extends IBaseResource> nextType : resourceTypes) { RuntimeResourceDefinition typeDef = myContext.getResourceDefinition(nextType); IFhirResourceDao<?> dao = myCallingDao.getDao(nextType); if (dao == null) { ourLog.debug("Don't have a DAO for type {}", nextType.getSimpleName()); continue; } int qualifierIndex = chain.indexOf(':'); String qualifier = null; if (qualifierIndex != -1) { qualifier = chain.substring(qualifierIndex); chain = chain.substring(0, qualifierIndex); } boolean isMeta = BaseHapiFhirDao.RESOURCE_META_PARAMS.containsKey(chain); RuntimeSearchParam param = null; if (!isMeta) { param = typeDef.getSearchParam(chain); if (param == null) { ourLog.debug("Type {} doesn't have search param {}", nextType.getSimpleName(), param); continue; } } IQueryParameterType chainValue; if (remainingChain != null) { if (param == null || param.getParamType() != RestSearchParameterTypeEnum.REFERENCE) { ourLog.debug("Type {} parameter {} is not a reference, can not chain {}", new Object[] { nextType.getSimpleName(), chain, remainingChain }); continue; } chainValue = new ReferenceParam(); chainValue.setValueAsQueryToken(myContext, theParamName, qualifier, resourceId); ((ReferenceParam) chainValue).setChain(remainingChain); } else if (isMeta) { IQueryParameterType type = BaseHapiFhirDao.newInstanceType(chain); type.setValueAsQueryToken(myContext, theParamName, qualifier, resourceId); chainValue = type; } else { chainValue = toParameterType(param, qualifier, resourceId); } foundChainMatch = true; Set<Long> pids = dao.searchForIds(chain, chainValue); if (pids.isEmpty()) { continue; } Predicate eq = from.get("myTargetResourcePid").in(pids); codePredicates.add(eq); } if (!foundChainMatch) { throw new InvalidRequestException( myContext.getLocalizer().getMessage(BaseHapiFhirResourceDao.class, "invalidParameterChain", theParamName + '.' + ref.getChain())); } } } else { throw new IllegalArgumentException( "Invalid token type (expecting ReferenceParam): " + params.getClass()); } } List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(createResourceLinkPathPredicate(theParamName, from)); predicates.add(builder.or(toArray(codePredicates))); createPredicateResourceId(builder, cq, predicates, from.get("mySourceResourcePid").as(Long.class)); createPredicateLastUpdatedForResourceLink(builder, from, predicates); cq.where(builder.and(toArray(predicates))); TypedQuery<Long> q = myEntityManager.createQuery(cq); doSetPids(new HashSet<Long>(q.getResultList())); }
From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java
@Override public List<ILocalAccountPerson> getPeople(LocalAccountQuery query) { final EntityManager entityManager = this.getEntityManager(); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb.createQuery(LocalAccountPersonImpl.class); final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery.from(LocalAccountPersonImpl.class); final CollectionJoin<LocalAccountPersonImpl, LocalAccountPersonAttributeImpl> attributes = accountRoot .join(LocalAccountPersonImpl_.attributes); final ListJoin<LocalAccountPersonAttributeImpl, String> attributeValues = attributes .join(LocalAccountPersonAttributeImpl_.values); //Due to the joins multiple rows are returned for each result criteriaQuery.distinct(true);//from w ww . j a v a 2 s .c om criteriaQuery.select(accountRoot); final List<Predicate> whereParts = new LinkedList<Predicate>(); final Map<Parameter<String>, String> params = new LinkedHashMap<Parameter<String>, String>(); // if a username has been specified, append it to the query if (query.getName() != null) { whereParts.add(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), this.nameParameter)); params.put(this.nameParameter, query.getName()); } //Build Predicate for each attribute being queried int paramCount = 0; for (Map.Entry<String, List<String>> entry : query.getAttributes().entrySet()) { final List<String> values = entry.getValue(); if (values == null) { continue; } //For each value create a Predicate checking the attribute name and value together for (final String value : values) { if (StringUtils.isBlank(value)) { continue; } //Create Parameter objects for the name and value, stick them in the params map for later use final ParameterExpression<String> nameParam = this.createParameterExpression(String.class, "attrName" + paramCount); final ParameterExpression<String> valueParam = this.createParameterExpression(String.class, "attrValue" + paramCount); params.put(nameParam, entry.getKey()); params.put(valueParam, "%" + value.toLowerCase() + "%"); //Build the and(eq, like) predicate and add it to the list of predicates for the where clause whereParts.add(cb.and(cb.equal(attributes.get(LocalAccountPersonAttributeImpl_.name), nameParam), cb.like(cb.lower(attributeValues.as(String.class)), valueParam))); paramCount++; } } //Add the Predicates to the where clause criteriaQuery.where(cb.or(whereParts.toArray(new Predicate[whereParts.size()]))); //Create the query final TypedQuery<LocalAccountPersonImpl> jpaQuery = this.createCachedQuery(criteriaQuery); //Add all of the stored up parameters to the query for (Map.Entry<Parameter<String>, String> entry : params.entrySet()) { final Parameter<String> parameter = entry.getKey(); final String value = entry.getValue(); jpaQuery.setParameter(parameter, value); } final List<LocalAccountPersonImpl> accounts = jpaQuery.getResultList(); return new ArrayList<ILocalAccountPerson>(accounts); }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected void attachSearchCriteria(SearchCriteria searchCriteria, From<?, ? extends Product> product, From<?, ? extends Sku> sku, List<Predicate> restrictions) { CriteriaBuilder builder = em.getCriteriaBuilder(); // Build out the filter criteria from the users request for (Entry<String, String[]> entry : searchCriteria.getFilterCriteria().entrySet()) { String key = entry.getKey(); List<String> eqValues = new ArrayList<String>(); List<String[]> rangeValues = new ArrayList<String[]>(); // Determine which path is the appropriate one to use Path<?> pathToUse;/*from ww w . ja va 2 s.c o m*/ if (key.contains("defaultSku.")) { pathToUse = sku; key = key.substring("defaultSku.".length()); } else if (key.contains("productAttributes.")) { pathToUse = product.join("productAttributes"); key = key.substring("productAttributes.".length()); restrictions.add(builder.equal(pathToUse.get("name").as(String.class), key)); key = "value"; } 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; } // Values can be equality checks (ie manufacturer=Dave's) or range checks, which take the form // key=range[minRange:maxRange]. Figure out what type of check this is for (String value : entry.getValue()) { if (value.contains("range[")) { String[] rangeValue = new String[] { value.substring(value.indexOf("[") + 1, value.indexOf(":")), value.substring(value.indexOf(":") + 1, value.indexOf("]")) }; rangeValues.add(rangeValue); } else { eqValues.add(value); } } // Add the equality range restriction with the "in" builder. That means that the query string // ?manufacturer=Dave&manufacturer=Bob would match either Dave or Bob if (eqValues.size() > 0) { restrictions.add(pathToUse.get(key).in(eqValues)); } // If we have any range restrictions, we need to build those too. Ranges are also "or"ed together, // such that specifying range[0:5] and range[10:null] for the same field would match items // that were valued between 0 and 5 OR over 10 for that field List<Predicate> rangeRestrictions = new ArrayList<Predicate>(); for (String[] range : rangeValues) { BigDecimal min = new BigDecimal(range[0]); BigDecimal max = null; if (range[1] != null && !range[1].equals("null")) { max = new BigDecimal(range[1]); } Predicate minRange = builder.greaterThan(pathToUse.get(key).as(BigDecimal.class), min); Predicate maxRange = null; if (max != null) { maxRange = builder.lessThan(pathToUse.get(key).as(BigDecimal.class), max); rangeRestrictions.add(builder.and(minRange, maxRange)); } else { rangeRestrictions.add(minRange); } } if (rangeRestrictions.size() > 0) { restrictions.add(builder.or(rangeRestrictions.toArray(new Predicate[rangeRestrictions.size()]))); } } }
From source file:org.easy.criteria.CriteriaComposer.java
/** * @param criteriaBuilder//w w w .j av a2 s. c o m * @param out */ @SuppressWarnings("unchecked") protected void generateHaving(final CriteriaBuilder criteriaBuilder, final List<Predicate> out) { // log.debug("generateHaving :"); Preconditions.checkNotNull(out); Preconditions.checkNotNull(criteriaBuilder); Preconditions.checkNotNull(root); if (_joins != null && _joins.size() > 0) { Set<Entry<JoinContainer<E>, CriteriaComposer<?>>> allSetJoins = _joins.entrySet(); for (Entry<JoinContainer<E>, CriteriaComposer<?>> joinEntry : allSetJoins) { CriteriaComposer<?> subCriteria = joinEntry.getValue(); if (subCriteria != null) subCriteria.generateHaving(criteriaBuilder, out); } } if (_havings != null) { List<Predicate> andPredicates = new ArrayList<Predicate>(0); List<Predicate> orPredicates = new ArrayList<Predicate>(0); LogicOperator lastOperator = LogicOperator.NONE; for (HavingContainer<E> havingContainer : _havings) { @SuppressWarnings("rawtypes") Expression expression = null; switch (havingContainer.function) { case COUNT: expression = criteriaBuilder.count(root.get(havingContainer.attribute)); break; case AVG: expression = criteriaBuilder.avg(root.get(havingContainer.attribute)); break; case SUM: expression = criteriaBuilder.sum(root.get(havingContainer.attribute)); break; case MAX: expression = criteriaBuilder.max(root.get(havingContainer.attribute)); break; case MIN: expression = criteriaBuilder.min(root.get(havingContainer.attribute)); break; } Predicate predicate = ComparisonOperatorProcessor.process(criteriaBuilder, expression, havingContainer.comparisionOperator, havingContainer.value); if (havingContainer.notOperator != null) predicate = ComparisonOperatorProcessor.negate(criteriaBuilder, predicate); LogicOperator nextOperator = havingContainer.logicOperator; if (nextOperator == LogicOperator.NONE && !nextOperator.equals(lastOperator)) nextOperator = lastOperator; switch (nextOperator) { case AND: case NONE: andPredicates.add(predicate); break; case OR: orPredicates.add(predicate); break; default: throw new java.lang.IllegalStateException( "Unknown operator found " + havingContainer.comparisionOperator.toString()); } lastOperator = nextOperator; } // end for if (andPredicates != null && andPredicates.size() > 0) out.add(criteriaBuilder.and(andPredicates.toArray(new Predicate[andPredicates.size()]))); if (orPredicates != null && orPredicates.size() > 0) out.add(criteriaBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()]))); } // end if }
From source file:org.easy.criteria.CriteriaComposer.java
/** * Adds all attributes to match and their values to the predicate. * // w w w .jav a2 s. c om * @param criteriaBuilder * @param out * - predicates */ @SuppressWarnings("unchecked") protected void generateWhere(final CriteriaBuilder criteriaBuilder, final List<Predicate> out) { // log.debug("generateWhereClaus :"); Preconditions.checkNotNull(out); Preconditions.checkNotNull(criteriaBuilder); Preconditions.checkNotNull(root); if (_joins != null && _joins.size() > 0) { Set<Entry<JoinContainer<E>, CriteriaComposer<?>>> allSetJoins = _joins.entrySet(); for (Entry<JoinContainer<E>, CriteriaComposer<?>> joinEntry : allSetJoins) { CriteriaComposer<?> subCriteria = joinEntry.getValue(); if (subCriteria != null) subCriteria.generateWhere(criteriaBuilder, out); } } if (_wheres != null) { List<Predicate> andPredicates = new ArrayList<Predicate>(0); List<Predicate> orPredicates = new ArrayList<Predicate>(0); LogicOperator lastOperator = LogicOperator.NONE; for (WhereContainer<E> where : _wheres) { Predicate predicate = ComparisonOperatorProcessor.process(criteriaBuilder, root.get(where.attribute), where.comparisionOperator, where.value); if (where.notOperator != null) predicate = criteriaBuilder.not(predicate); LogicOperator nextOperator = where.logicOperator; if (nextOperator == LogicOperator.NONE && !nextOperator.equals(lastOperator)) nextOperator = lastOperator; switch (nextOperator) { case AND: case NONE: andPredicates.add(predicate); break; case OR: orPredicates.add(predicate); break; default: throw new java.lang.IllegalStateException( "Unknown operator found " + where.comparisionOperator.toString()); } lastOperator = nextOperator; } // end for if (andPredicates != null && andPredicates.size() > 0) out.add(criteriaBuilder.and(andPredicates.toArray(new Predicate[andPredicates.size()]))); if (orPredicates != null && orPredicates.size() > 0) out.add(criteriaBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()]))); } // end if }
From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java
private Subquery<RuleResponsibilityBo> addResponsibilityCriteria(CriteriaQuery<RuleBaseValues> query, Collection<String> workgroupIds, String workflowId, Collection actionRequestCodes, Boolean searchUser, Boolean searchUserInWorkgroups) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); Subquery<RuleResponsibilityBo> subquery = query.subquery(RuleResponsibilityBo.class); Root fromResp = subquery.from(RuleResponsibilityBo.class); List<javax.persistence.criteria.Predicate> respPredicates = new ArrayList<javax.persistence.criteria.Predicate>(); List<javax.persistence.criteria.Predicate> ruleRespNamePredicates = new ArrayList<javax.persistence.criteria.Predicate>(); List<javax.persistence.criteria.Predicate> userNamePreds = new ArrayList<javax.persistence.criteria.Predicate>(); List<javax.persistence.criteria.Predicate> workgroupPreds = new ArrayList<javax.persistence.criteria.Predicate>(); if ((actionRequestCodes != null) && (!actionRequestCodes.isEmpty())) { Expression<String> exp = fromResp.get("actionRequestedCd"); javax.persistence.criteria.Predicate actionRequestPredicate = exp.in(actionRequestCodes); respPredicates.add(actionRequestPredicate); }/* www .j a va 2s. c o m*/ if (!org.apache.commons.lang.StringUtils.isEmpty(workflowId)) { // workflow user id exists if (searchUser != null && searchUser) { // searching user wishes to search for rules specific to user userNamePreds.add(cb.like(fromResp.get("ruleResponsibilityName"), workflowId)); userNamePreds.add(cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_WORKFLOW_ID)); javax.persistence.criteria.Predicate[] preds = userNamePreds .toArray(new javax.persistence.criteria.Predicate[userNamePreds.size()]); ruleRespNamePredicates.add(cb.and(preds)); } if ((searchUserInWorkgroups != null && searchUserInWorkgroups) && (workgroupIds != null) && (!workgroupIds.isEmpty())) { // at least one workgroup id exists and user wishes to search on workgroups Expression<String> exp = fromResp.get("ruleResponsibilityName"); javax.persistence.criteria.Predicate groupIdPredicate = exp.in(workgroupIds); workgroupPreds.add(groupIdPredicate); workgroupPreds.add(cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID)); javax.persistence.criteria.Predicate[] preds = workgroupPreds .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]); ruleRespNamePredicates.add(cb.and(preds)); } } else if ((workgroupIds != null) && (workgroupIds.size() == 1)) { // no user and one workgroup id workgroupPreds.add(cb.like(fromResp.get("ruleResponsibilityName"), workgroupIds.iterator().next())); workgroupPreds.add( cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID)); javax.persistence.criteria.Predicate[] preds = workgroupPreds .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]); ruleRespNamePredicates.add(cb.and(preds)); } else if ((workgroupIds != null) && (workgroupIds.size() > 1)) { // no user and more than one workgroup id Expression<String> exp = fromResp.get("ruleResponsibilityName"); javax.persistence.criteria.Predicate groupIdPredicate = exp.in(workgroupIds); workgroupPreds.add( cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID)); javax.persistence.criteria.Predicate[] preds = workgroupPreds .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]); ruleRespNamePredicates.add(cb.and(preds)); } if (!ruleRespNamePredicates.isEmpty()) { javax.persistence.criteria.Predicate[] preds = ruleRespNamePredicates .toArray(new javax.persistence.criteria.Predicate[ruleRespNamePredicates.size()]); respPredicates.add(cb.or(preds)); } if (!respPredicates.isEmpty()) { javax.persistence.criteria.Predicate[] preds = respPredicates .toArray(new javax.persistence.criteria.Predicate[respPredicates.size()]); subquery.where(preds); subquery.select(fromResp.get("ruleBaseValuesId")); return subquery; } return null; }
From source file:org.medici.bia.dao.volume.VolumeDAOJpaImpl.java
/** * {@inheritDoc}/*w ww.ja v a 2 s .c o m*/ */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Page searchVolumes(String text, PaginationFilter paginationFilter) throws PersistenceException { // Create criteria objects CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); Page page = new Page(paginationFilter); if (paginationFilter.getTotal() == null) { CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class); Root<Volume> rootCount = criteriaQueryCount.from(Volume.class); criteriaQueryCount.select(criteriaBuilder.count(rootCount)); List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add( criteriaBuilder.like((Expression) rootCount.get("serieList").get("title"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) rootCount.get("serieList").get("subTitle1"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) rootCount.get("serieList").get("subTitle2"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) rootCount.get("orgNotes"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) rootCount.get("recips"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) rootCount.get("researcher"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) rootCount.get("senders"), "%" + text + "%")); //If we omiss criteriaBuilder.or every predicate is in conjunction with others criteriaQueryCount.where(criteriaBuilder.or(predicates.toArray(new Predicate[] {}))); TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount); page.setTotal(new Long((Long) typedQueryCount.getSingleResult())); } CriteriaQuery<Volume> criteriaQuery = criteriaBuilder.createQuery(Volume.class); Root<Volume> root = criteriaQuery.from(Volume.class); //We need to duplicate predicates beacause they are link to Root element List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("title"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("subTitle1"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("subTitle2"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) root.get("orgNotes"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) root.get("recips"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) root.get("researcher"), "%" + text + "%")); predicates.add(criteriaBuilder.like((Expression) root.get("senders"), "%" + text + "%")); //If we omiss criteriaBuilder.or every predicate is in conjunction with others criteriaQuery.where(criteriaBuilder.or(predicates.toArray(new Predicate[] {}))); criteriaQuery.orderBy(criteriaBuilder.asc(root.get("summaryId"))); // Set values in predicate's elements TypedQuery<Volume> typedQuery = getEntityManager().createQuery(criteriaQuery); typedQuery.setFirstResult(paginationFilter.getFirstRecord()); typedQuery.setMaxResults(paginationFilter.getLength()); page.setList(typedQuery.getResultList()); return page; }
From source file:org.niord.core.area.AreaService.java
/** * Searches for areas matching the given search params * * @param params the sesarch params//from w w w.ja va 2 s. c o m * @return the search result */ @SuppressWarnings("all") public List<Area> searchAreas(AreaSearchParams params) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Area> areaQuery = cb.createQuery(Area.class); Root<Area> areaRoot = areaQuery.from(Area.class); // Build the predicate CriteriaHelper<Area> criteriaHelper = new CriteriaHelper<>(cb, areaQuery); // Match the name Join<Area, AreaDesc> descs = areaRoot.join("descs", JoinType.LEFT); if (params.isExact()) { criteriaHelper.equalsIgnoreCase(descs.get("name"), params.getName()); } else { criteriaHelper.like(descs.get("name"), params.getName()); } // Optionally, match the language if (StringUtils.isNotBlank(params.getLanguage())) { criteriaHelper.equals(descs.get("lang"), params.getLanguage()); } // Optionally, match the parent if (params.getParentId() != null) { areaRoot.join("parent", JoinType.LEFT); Path<Area> parent = areaRoot.get("parent"); criteriaHelper.equals(parent.get("id"), params.getParentId()); } // Assemple lineage filters from search domain and areas Set<String> lineages = new HashSet<>(); // Optionally, filter by the areas associated with the specified domain if (StringUtils.isNotBlank(params.getDomain())) { Domain d = domainService.findByDomainId(params.getDomain()); if (d != null && d.getAreas().size() > 0) { d.getAreas().forEach(a -> lineages.add(a.getLineage())); } } // Optionally, filter by area subtrees if (params.getAreaIds() != null && !params.getAreaIds().isEmpty()) { getAreaDetails(params.getAreaIds()).forEach(a -> lineages.add(a.getLineage())); } // If defined, apply the area lineage filter if (!lineages.isEmpty()) { Predicate[] areaMatch = lineages.stream() .map(lineage -> cb.like(areaRoot.get("lineage"), lineage + "%")).toArray(Predicate[]::new); criteriaHelper.add(cb.or(areaMatch)); } // Optionally, search by type if (params.getType() != null) { criteriaHelper.add(cb.equal(areaRoot.get("type"), params.getType())); } // Optionally, require that the area has an associated geometry if (params.isGeometry()) { criteriaHelper.add(cb.isNotNull(areaRoot.get("geometry"))); } // Optionally, require that the area has an messageSorting type if (params.isMessageSorting()) { criteriaHelper.add(cb.isNotNull(areaRoot.get("messageSorting"))); } // Unless the "inactive" search flag is set, only include active areas. if (!params.isInactive()) { criteriaHelper.add(cb.equal(areaRoot.get("active"), true)); } // Compute the sort order List<Order> sortOrders = new ArrayList<>(); if (TREE_SORT_ORDER.equals(params.getSortBy())) { Arrays.asList("treeSortOrder", "siblingSortOrder", "id").forEach(field -> { if (params.getSortOrder() == PagedSearchParamsVo.SortOrder.ASC) { sortOrders.add(cb.asc(areaRoot.get(field))); } else { sortOrders.add(cb.desc(areaRoot.get(field))); } }); } // Complete the query areaQuery.select(areaRoot).distinct(true).where(criteriaHelper.where()).orderBy(sortOrders); // Execute the query and update the search result return em.createQuery(areaQuery).setMaxResults(params.getMaxSize()).getResultList(); }
From source file:org.niord.core.category.CategoryService.java
/** * Searches for categories matching the given term in the given language * * @param params the sesarch params/* w w w .j a va 2 s .com*/ * @return the search result */ @SuppressWarnings("all") public List<Category> searchCategories(CategorySearchParams params) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Category> categoryQuery = cb.createQuery(Category.class); Root<Category> categoryRoot = categoryQuery.from(Category.class); // Build the predicate CriteriaHelper<Category> criteriaHelper = new CriteriaHelper<>(cb, categoryQuery); // Match the name Join<Category, CategoryDesc> descs = categoryRoot.join("descs", JoinType.LEFT); if (params.isExact()) { criteriaHelper.equalsIgnoreCase(descs.get("name"), params.getName()); } else { criteriaHelper.like(descs.get("name"), params.getName()); } // Optionally, match the language if (StringUtils.isNotBlank(params.getLanguage())) { criteriaHelper.equals(descs.get("lang"), params.getLanguage()); } // Optionally, match the parent if (params.getParentId() != null) { categoryRoot.join("parent", JoinType.LEFT); Path<Category> parent = categoryRoot.get("parent"); criteriaHelper.equals(parent.get("id"), params.getParentId()); } // Optionally, filter by the domains associated with the current domain if (StringUtils.isNotBlank(params.getDomain())) { Domain d = domainService.findByDomainId(params.getDomain()); if (d != null && d.getCategories().size() > 0) { Predicate[] categoryMatch = d.getCategories().stream() .map(c -> cb.like(categoryRoot.get("lineage"), c.getLineage() + "%")) .toArray(Predicate[]::new); criteriaHelper.add(cb.or(categoryMatch)); } } // Unless the "inactive" search flag is set, only include active categories. if (!params.isInactive()) { criteriaHelper.add(cb.equal(categoryRoot.get("active"), true)); } // Complete the query categoryQuery.select(categoryRoot).distinct(true).where(criteriaHelper.where()); //.orderBy(cb.asc(cb.locate(cb.lower(descs.get("name")), name.toLowerCase()))); // Execute the query and update the search result return em.createQuery(categoryQuery).setMaxResults(params.getMaxSize()).getResultList(); }