List of usage examples for javax.persistence.criteria CriteriaBuilder conjunction
Predicate conjunction();
From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java
/** * @see ??JPA/*from ww w .j a va 2 s .c o 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: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; }// www . 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.ibankapp.base.persistence.validation.validator.UniqueValidator.java
@SuppressWarnings("unchecked") public static <T> void validate(T bean, EntityManager em) { EntityInformation ei = new EntityInformation(bean.getClass(), em.getMetamodel()); Iterable<String> idAttributeNames = ei.getIdAttributeNames(); List<Unique> uniqueList = new ArrayList<>(); if (bean.getClass().isAnnotationPresent(Uniques.class)) { Uniques uniques = bean.getClass().getAnnotation(Uniques.class); Collections.addAll(uniqueList, uniques.constraints()); }/*from w w w . j av a2 s .co m*/ if (bean.getClass().isAnnotationPresent(Unique.class)) { uniqueList.add(bean.getClass().getAnnotation(Unique.class)); } for (Unique unique : uniqueList) { String[] properties = unique.properties(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<?> c = cb.createQuery(bean.getClass()); Root<?> root = c.from(bean.getClass()); Predicate condition = cb.conjunction(); try { for (String idAttributeName : idAttributeNames) { condition = cb.and(condition, cb.notEqual(root.get(idAttributeName), PropertyUtils.getProperty(bean, idAttributeName))); } for (String property : properties) { condition = cb.and(condition, cb.equal(root.get(property), PropertyUtils.getProperty(bean, property))); } } catch (Exception e) { throw new BaseException("E-BASE-000001", e.getMessage()).initCause(e); } c.where(condition); int count = em.createQuery(c).getResultList().size(); if (count != 0) { throw new BaseException("E-BASE-000008", unique.message()); } } }
From source file:org.xiaoqiaotq.util.persistence.DynamicSpecifications.java
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz) { return new Specification<T>() { @Override/* w w w . j a va 2 s .c o 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]); for (int i = 1; i < names.length; i++) { expression = expression.get(names[i]); } // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case NEQ: predicates.add(builder.notEqual(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; } } // ? and ??? if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } } return builder.conjunction(); } }; }