List of usage examples for javax.persistence.criteria CriteriaBuilder like
Predicate like(Expression<String> x, String pattern);
From source file:com.zero.dao.impl.BaseDaoImpl.java
private void addRestrictions(CriteriaQuery<T> criteriaQuery, List<Filter> filters) { if (criteriaQuery == null || filters == null || filters.isEmpty()) { return;//from ww w . j a v a 2s .co m } Root<T> root = getRoot(criteriaQuery); if (root == null) { return; } CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); Predicate restrictions = criteriaQuery.getRestriction() != null ? criteriaQuery.getRestriction() : criteriaBuilder.conjunction(); for (Filter filter : filters) { if (filter == null || StringUtils.isEmpty(filter.getProperty())) { continue; } if (filter.getOperator() == Operator.eq && filter.getValue() != null) { if (filter.getIgnoreCase() != null && filter.getIgnoreCase() && filter.getValue() instanceof String) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(criteriaBuilder.lower(root.<String>get(filter.getProperty())), ((String) filter.getValue()).toLowerCase())); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get(filter.getProperty()), filter.getValue())); } } else if (filter.getOperator() == Operator.ne && filter.getValue() != null) { if (filter.getIgnoreCase() != null && filter.getIgnoreCase() && filter.getValue() instanceof String) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.notEqual(criteriaBuilder.lower(root.<String>get(filter.getProperty())), ((String) filter.getValue()).toLowerCase())); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.notEqual(root.get(filter.getProperty()), filter.getValue())); } } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.gt(root.<Number>get(filter.getProperty()), (Number) filter.getValue())); } else if (filter.getOperator() == Operator.lt && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lt(root.<Number>get(filter.getProperty()), (Number) filter.getValue())); } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get(filter.getProperty()), (Number) filter.getValue())); } else if (filter.getOperator() == Operator.le && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get(filter.getProperty()), (Number) filter.getValue())); } else if (filter.getOperator() == Operator.like && filter.getValue() != null && filter.getValue() instanceof String) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.<String>get(filter.getProperty()), (String) filter.getValue())); } else if (filter.getOperator() == Operator.in && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).in(filter.getValue())); } else if (filter.getOperator() == Operator.isNull) { restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNull()); } else if (filter.getOperator() == Operator.isNotNull) { restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNotNull()); } } criteriaQuery.where(restrictions); }
From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java
/** * @see ??JPA/*from ww w . j a v a2s .co m*/ * @param filters * @param entityClazz * @param isDistinct trueSQLdistinctfalse? * @return */ public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) { return new Specification<T>() { @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (orderParams != null && orderParams.size() > 0) { /* CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class); Root<Foo> from = criteriaQuery.from(Foo.class); CriteriaQuery<Foo> select = criteriaQuery.select(from); criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name"))); */ List<Order> orders = new ArrayList<Order>(orderParams.size()); for (OrderParam orderParam : orderParams) { if (orderParam != null && orderParam.getField() != null) { String fields[] = StringUtil.split(orderParam.getField(), '.'); Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]); for (int i = 1, len = fields.length; i < len; ++i) { expression = expression.get(fields[i]); } if (expression != null) { Order order = (orderParam.getType() == null || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression) : builder.desc(expression); orders.add(order); // query.orderBy(order); } } } query.orderBy(orders); } query.distinct(isDistinct); if (Collections3.isNotEmpty(filters)) { 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 = null; ////// ? boolean hasJoin = names[0].startsWith("[join]"); String fn = hasJoin ? names[0].substring(6) : names[0]; boolean isNotDateType = !(filter.value instanceof Date); try { expression = hasJoin ? root.join(fn) : root.get(fn); if (isNotDateType && isDateType(expression.getJavaType())) { // filter.value?? filter.value = parseDate(filter.value.toString(), filter.operator); } } catch (Exception e) { // logger.error(e.getMessage(), e); continue; // ?? } boolean isPropertyNotValid = false; for (int i = 1; i < names.length; i++) { try { expression = expression.get(names[i]); if (isNotDateType && isDateType(expression.getJavaType())) { filter.value = parseDate(filter.value.toString(), filter.operator); } } catch (Exception e) { // logger.error(e.getMessage(), e); isPropertyNotValid = true; // break; // ?? } } if (expression == null || isPropertyNotValid) { continue; } /////// // 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 ORLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.like(expression, "%" + values[i] + "%"); } predicates.add(builder.or(like)); } break; case ANDLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.like(expression, "%" + values[i] + "%"); } predicates.add(builder.and(like)); } break; case ANDNOTLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.notLike(expression, "%" + values[i] + "%"); } predicates.add(builder.and(like)); } break; case OREQ: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.equal(expression, values[i]); } predicates.add(builder.or(like)); } break; case ANDNOTEQ: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.notEqual(expression, values[i]); } predicates.add(builder.and(like)); } break; case NOTEQ: predicates.add(builder.notEqual(expression, (Comparable) filter.value)); break; case NOTLIKE: predicates.add(builder.notLike(expression, "%" + filter.value + "%")); break; case NULL: predicates.add(builder.isNull(expression)); break; case NOTNULL: predicates.add(builder.isNotNull(expression)); break; // case IN: // predicates.add(builder.in(expression).in(values)); // break; } } // ? and ??? if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } } return builder.conjunction(); } }; }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private Predicate createPredicateString(IQueryParameterType theParameter, String theParamName, CriteriaBuilder theBuilder, From<ResourceIndexedSearchParamString, ResourceIndexedSearchParamString> theFrom) { String rawSearchTerm;/*from w w w. j a v a 2 s . com*/ if (theParameter instanceof TokenParam) { TokenParam id = (TokenParam) theParameter; if (!id.isText()) { throw new IllegalStateException("Trying to process a text search on a non-text token parameter"); } rawSearchTerm = id.getValue(); } else if (theParameter instanceof StringParam) { StringParam id = (StringParam) theParameter; rawSearchTerm = id.getValue(); } else if (theParameter instanceof IPrimitiveDatatype<?>) { IPrimitiveDatatype<?> id = (IPrimitiveDatatype<?>) theParameter; rawSearchTerm = id.getValueAsString(); } else { throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass()); } if (rawSearchTerm.length() > ResourceIndexedSearchParamString.MAX_LENGTH) { throw new InvalidRequestException("Parameter[" + theParamName + "] has length (" + rawSearchTerm.length() + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamString.MAX_LENGTH + "): " + rawSearchTerm); } String likeExpression = BaseHapiFhirDao.normalizeString(rawSearchTerm); likeExpression = createLeftMatchLikeExpression(likeExpression); Predicate singleCode = theBuilder.like(theFrom.get("myValueNormalized").as(String.class), likeExpression); if (theParameter instanceof StringParam && ((StringParam) theParameter).isExact()) { Predicate exactCode = theBuilder.equal(theFrom.get("myValueExact"), rawSearchTerm); singleCode = theBuilder.and(singleCode, exactCode); } return singleCode; }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateUri(String theParamName, List<? extends IQueryParameterType> theList) { if (Boolean.TRUE.equals(theList.get(0).getMissing())) { addPredicateParamMissing("myParamsUri", theParamName, ResourceIndexedSearchParamUri.class); return;// w w w. j a va2 s . com } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceIndexedSearchParamUri> from = cq.from(ResourceIndexedSearchParamUri.class); cq.select(from.get("myResourcePid").as(Long.class)); List<Predicate> codePredicates = new ArrayList<Predicate>(); for (IQueryParameterType nextOr : theList) { IQueryParameterType params = nextOr; if (addPredicateMissingFalseIfPresent(builder, theParamName, from, codePredicates, nextOr)) { continue; } if (params instanceof UriParam) { UriParam param = (UriParam) params; String value = param.getValue(); if (value == null) { continue; } Path<Object> fromObj = from.get("myUri"); Predicate predicate; if (param.getQualifier() == UriParamQualifierEnum.ABOVE) { /* * :above is an inefficient query- It means that the user is supplying a more specific URL (say * http://example.com/foo/bar/baz) and that we should match on any URLs that are less * specific but otherwise the same. For example http://example.com and http://example.com/foo would both * match. * * We do this by querying the DB for all candidate URIs and then manually checking each one. This isn't * very efficient, but this is also probably not a very common type of query to do. * * If we ever need to make this more efficient, lucene could certainly be used as an optimization. */ ourLog.info("Searching for candidate URI:above parameters for Resource[{}] param[{}]", myResourceName, theParamName); Collection<String> candidates = myResourceIndexedSearchParamUriDao .findAllByResourceTypeAndParamName(myResourceName, theParamName); List<String> toFind = new ArrayList<String>(); for (String next : candidates) { if (value.length() >= next.length()) { if (value.substring(0, next.length()).equals(next)) { toFind.add(next); } } } if (toFind.isEmpty()) { continue; } predicate = fromObj.as(String.class).in(toFind); } else if (param.getQualifier() == UriParamQualifierEnum.BELOW) { predicate = builder.like(fromObj.as(String.class), createLeftMatchLikeExpression(value)); } else { predicate = builder.equal(fromObj.as(String.class), value); } codePredicates.add(predicate); } else { throw new IllegalArgumentException("Invalid URI type: " + params.getClass()); } } if (codePredicates.isEmpty()) { doSetPids(new HashSet<Long>()); return; } List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(builder.equal(from.get("myResourceType"), myResourceName)); predicates.add(builder.equal(from.get("myParamName"), theParamName)); predicates.add(builder.or(toArray(codePredicates))); createPredicateResourceId(builder, cq, predicates, from.get("myResourcePid").as(Long.class)); cq.where(builder.and(toArray(predicates))); TypedQuery<Long> q = myEntityManager.createQuery(cq); doSetPids(new HashSet<Long>(q.getResultList())); }
From source file:com.sammyun.dao.impl.BaseDaoImpl.java
private void addRestrictions(CriteriaQuery<T> criteriaQuery, List<Filter> filters) { if (criteriaQuery == null || filters == null || filters.isEmpty()) { return;//from w w w .j a v a 2s . co m } Root<T> root = getRoot(criteriaQuery); if (root == null) { return; } CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); Predicate restrictions = criteriaQuery.getRestriction() != null ? criteriaQuery.getRestriction() : criteriaBuilder.conjunction(); for (Filter filter : filters) { if (filter == null || StringUtils.isEmpty(filter.getProperty())) { continue; } /** */ if (filter.getMold() == Mold.dl || filter.getMold() == Mold.dg) { if (filter.getOperator() == Operator.lt && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThan(root.<Date>get(filter.getProperty()), DateUtil.parseDate(filter.getValue().toString()))); } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThan(root.<Date>get(filter.getProperty()), DateUtil.parseDate(filter.getValue().toString()))); } else if (filter.getOperator() == Operator.le && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(root.<Date>get(filter.getProperty()), DateUtil.parseDate(filter.getValue().toString()))); } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(root.<Date>get(filter.getProperty()), DateUtil.parseDate(filter.getValue().toString()))); } } else { if (filter.getOperator() == Operator.eq && filter.getValue() != null) { if (filter.getIgnoreCase() != null && filter.getIgnoreCase() && filter.getValue() instanceof String) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(criteriaBuilder.lower(root.<String>get(filter.getProperty())), ((String) filter.getValue()).toLowerCase())); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get(filter.getProperty()), filter.getValue())); } } else if (filter.getOperator() == Operator.ne && filter.getValue() != null) { if (filter.getIgnoreCase() != null && filter.getIgnoreCase() && filter.getValue() instanceof String) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.notEqual( criteriaBuilder.lower(root.<String>get(filter.getProperty())), ((String) filter.getValue()).toLowerCase())); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.notEqual(root.get(filter.getProperty()), filter.getValue())); } } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.gt(root.<Number>get(filter.getProperty()), (Number) filter.getValue())); } else if (filter.getOperator() == Operator.lt && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lt(root.<Number>get(filter.getProperty()), (Number) filter.getValue())); } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get(filter.getProperty()), (Number) filter.getValue())); } else if (filter.getOperator() == Operator.le && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get(filter.getProperty()), (Number) filter.getValue())); } else if (filter.getOperator() == Operator.like && filter.getValue() != null && filter.getValue() instanceof String) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder .like(root.<String>get(filter.getProperty()), (String) filter.getValue())); } else if (filter.getOperator() == Operator.in && filter.getValue() != null) { restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).in(filter.getValue())); } else if (filter.getOperator() == Operator.isNull) { restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNull()); } else if (filter.getOperator() == Operator.isNotNull) { restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNotNull()); } } } criteriaQuery.where(restrictions); }
From source file:org.apache.openejb.util.proxy.QueryProxy.java
private <T> Query createFinderQuery(final EntityManager entityManager, final String methodName, final Class<T> entityType, final Object[] args) { final List<String> conditions = parseMethodName(methodName); final EntityType<T> et = entityManager.getMetamodel().entity(entityType); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Object> query = cb.createQuery(); final Root<T> from = query.from(entityType); query = query.select(from);//from w w w . ja v a2 s. c o m int i = 0; Predicate where = null; for (final String condition : conditions) { final SingularAttribute<? super T, ?> attribute = et.getSingularAttribute(condition); final Path<?> path = from.get(attribute); final Class<?> javaType = attribute.getType().getJavaType(); final Predicate currentClause; if (javaType.equals(String.class)) { currentClause = cb.like((Expression<String>) path, (String) args[i++]); } else if (Number.class.isAssignableFrom(javaType) || javaType.isPrimitive()) { currentClause = cb.equal(path, args[i++]); } else { LOGGER.warning("field " + condition + " not found, ignoring"); continue; } if (where == null) { where = currentClause; } else { where = cb.and(where, currentClause); } } if (where != null) { query = query.where(where); } // pagination final TypedQuery<?> emQuery = entityManager.createQuery(query); if (args != null && args.length == conditions.size() + 2 && isInt(args[args.length - 2].getClass()) && isInt(args[args.length - 1].getClass())) { final int first = (Integer) args[args.length - 2]; final int max = (Integer) args[args.length - 1]; emQuery.setFirstResult(first); emQuery.setMaxResults(max); } return emQuery; }
From source file:org.apache.openmeetings.data.user.UserManager.java
/** * suche eines Bentzers/*from w ww. ja v a 2s . c o m*/ * * @param user_level * @param searchstring * @param max * @param start * @return */ public List<User> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start, String orderby, boolean asc) { if (authLevelUtil.checkAdminLevel(user_level)) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> c = cq.from(User.class); Expression<String> literal = cb.literal("%" + searchstring + "%"); Path<String> path = c.get(searchcriteria); Predicate predicate = cb.like(path, literal); Predicate condition = cb.notEqual(c.get("deleted"), true); cq.where(condition, predicate); cq.distinct(asc); if (asc) { cq.orderBy(cb.asc(c.get(orderby))); } else { cq.orderBy(cb.desc(c.get(orderby))); } TypedQuery<User> q = em.createQuery(cq); q.setFirstResult(start); q.setMaxResults(max); List<User> contactsZ = q.getResultList(); return contactsZ; } catch (Exception ex2) { log.error("searchUser", ex2); } } return null; }
From source file:org.apache.ranger.service.XTrxLogService.java
private Predicate generatePredicate(SearchCriteria searchCriteria, EntityManager em, CriteriaBuilder criteriaBuilder, Root<VXXTrxLog> rootEntityType) { Predicate predicate = criteriaBuilder.conjunction(); Map<String, Object> paramList = searchCriteria.getParamList(); if (CollectionUtils.isEmpty(paramList)) { return predicate; }/*from ww w . j a v a2 s . c o m*/ Metamodel entityMetaModel = em.getMetamodel(); EntityType<VXXTrxLog> entityType = entityMetaModel.entity(VXXTrxLog.class); for (Map.Entry<String, Object> entry : paramList.entrySet()) { String key = entry.getKey(); for (SearchField searchField : searchFields) { if (!key.equalsIgnoreCase(searchField.getClientFieldName())) { continue; } String fieldName = searchField.getFieldName(); if (!StringUtils.isEmpty(fieldName)) { fieldName = fieldName.contains(".") ? fieldName.substring(fieldName.indexOf(".") + 1) : fieldName; } Object paramValue = entry.getValue(); boolean isListValue = false; if (paramValue != null && paramValue instanceof Collection) { isListValue = true; } // build where clause depending upon given parameters if (SearchField.DATA_TYPE.STRING.equals(searchField.getDataType())) { // build where clause for String datatypes SingularAttribute attr = entityType.getSingularAttribute(fieldName); if (attr != null) { Predicate stringPredicate = null; if (SearchField.SEARCH_TYPE.PARTIAL.equals(searchField.getSearchType())) { String val = "%" + paramValue + "%"; stringPredicate = criteriaBuilder.like(rootEntityType.get(attr), val); } else { stringPredicate = criteriaBuilder.equal(rootEntityType.get(attr), paramValue); } predicate = criteriaBuilder.and(predicate, stringPredicate); } } else if (SearchField.DATA_TYPE.INT_LIST.equals(searchField.getDataType()) || isListValue && SearchField.DATA_TYPE.INTEGER.equals(searchField.getDataType())) { // build where clause for integer lists or integers datatypes Collection<Number> intValueList = null; if (paramValue != null && (paramValue instanceof Integer || paramValue instanceof Long)) { intValueList = new ArrayList<Number>(); intValueList.add((Number) paramValue); } else { intValueList = (Collection<Number>) paramValue; } for (Number value : intValueList) { SingularAttribute attr = entityType.getSingularAttribute(fieldName); if (attr != null) { Predicate intPredicate = criteriaBuilder.equal(rootEntityType.get(attr), value); predicate = criteriaBuilder.and(predicate, intPredicate); } } } else if (SearchField.DATA_TYPE.DATE.equals(searchField.getDataType())) { // build where clause for date datatypes Date fieldValue = (Date) paramList.get(searchField.getClientFieldName()); if (fieldValue != null && searchField.getCustomCondition() == null) { SingularAttribute attr = entityType.getSingularAttribute(fieldName); Predicate datePredicate = null; if (SearchField.SEARCH_TYPE.LESS_THAN.equals(searchField.getSearchType())) { datePredicate = criteriaBuilder.lessThan(rootEntityType.get(attr), fieldValue); } else if (SearchField.SEARCH_TYPE.LESS_EQUAL_THAN.equals(searchField.getSearchType())) { datePredicate = criteriaBuilder.lessThanOrEqualTo(rootEntityType.get(attr), fieldValue); } else if (SearchField.SEARCH_TYPE.GREATER_THAN.equals(searchField.getSearchType())) { datePredicate = criteriaBuilder.greaterThan(rootEntityType.get(attr), fieldValue); } else if (SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN.equals(searchField.getSearchType())) { datePredicate = criteriaBuilder.greaterThanOrEqualTo(rootEntityType.get(attr), fieldValue); } else { datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue); } predicate = criteriaBuilder.and(predicate, datePredicate); } } } } return predicate; }
From source file:org.apache.rave.portal.repository.impl.JpaWidgetRepository.java
private Predicate[] getStatusAndTypeAndFreeTextPredicates(CriteriaBuilder cb, Root<JpaWidget> widgetType, WidgetStatus widgetStatus, String type, String searchTerm) { List<Predicate> predicates = new ArrayList<Predicate>(); if (StringUtils.isNotBlank(searchTerm)) { predicates.add(/*from w w w . j a v a 2s . c o m*/ cb.or(cb.like(cb.lower(getTitleField(widgetType)), getLowercaseWildcardSearchTerm(searchTerm)), cb.like(cb.lower(getDescriptionField(widgetType)), getLowercaseWildcardSearchTerm(searchTerm)))); } if (StringUtils.isNotBlank(type)) { predicates.add(cb.and(cb.equal(getTypeField(widgetType), type))); } if (widgetStatus != null) { predicates.add(cb.and(cb.equal(getWidgetStatusField(widgetType), widgetStatus))); } return predicates.toArray(new Predicate[predicates.size()]); }
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);//ww w. j a va 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); }