List of usage examples for javax.persistence.criteria CriteriaBuilder greaterThan
<Y extends Comparable<? super Y>> Predicate greaterThan(Expression<? extends Y> x, Y y);
From source file:net.groupbuy.dao.impl.ProductDaoImpl.java
public List<Product> findList(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags, Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert, OrderType orderType, Integer count, List<Filter> filters, List<Order> orders) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class); Root<Product> root = criteriaQuery.from(Product.class); criteriaQuery.select(root);/*w w w . j av a 2 s . com*/ Predicate restrictions = criteriaBuilder.conjunction(); if (productCategory != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory), criteriaBuilder.like(root.get("productCategory").<String>get("treePath"), "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId() + ProductCategory.TREE_PATH_SEPARATOR + "%"))); } if (brand != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand)); } if (promotion != null) { Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot1 = subquery1.from(Product.class); subquery1.select(subqueryRoot1); subquery1.where(criteriaBuilder.equal(subqueryRoot1, root), criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion)); Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot2 = subquery2.from(Product.class); subquery2.select(subqueryRoot2); subquery2.where(criteriaBuilder.equal(subqueryRoot2, root), criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion)); Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot3 = subquery3.from(Product.class); subquery3.select(subqueryRoot3); subquery3.where(criteriaBuilder.equal(subqueryRoot3, root), criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1), criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3))); } if (tags != null && !tags.isEmpty()) { Subquery<Product> subquery = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot = subquery.from(Product.class); subquery.select(subqueryRoot); subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery)); } if (attributeValue != null) { for (Entry<Attribute, String> entry : attributeValue.entrySet()) { String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX + entry.getKey().getPropertyIndex(); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get(propertyName), entry.getValue())); } } if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) { BigDecimal temp = startPrice; startPrice = endPrice; endPrice = temp; } if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("price"), startPrice)); } if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("price"), endPrice)); } if (isMarketable != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isMarketable"), isMarketable)); } if (isList != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList)); } if (isTop != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop)); } if (isGift != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift)); } Path<Integer> stock = root.get("stock"); Path<Integer> allocatedStock = root.get("allocatedStock"); if (isOutOfStock != null) { if (isOutOfStock) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock), criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock)); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock, allocatedStock))); } } if (isStockAlert != null) { Setting setting = SettingUtils.get(); if (isStockAlert) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock), criteriaBuilder.lessThanOrEqualTo(stock, criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock, criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())))); } } criteriaQuery.where(restrictions); if (orderType == OrderType.priceAsc) { orders.add(Order.asc("price")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.priceDesc) { orders.add(Order.desc("price")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.salesDesc) { orders.add(Order.desc("sales")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.scoreDesc) { orders.add(Order.desc("score")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.dateDesc) { orders.add(Order.desc("createDate")); } else { orders.add(Order.desc("isTop")); orders.add(Order.desc("modifyDate")); } return super.findList(criteriaQuery, null, count, filters, orders); }
From source file:net.groupbuy.dao.impl.ProductDaoImpl.java
public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags, Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert, OrderType orderType, Pageable pageable) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class); Root<Product> root = criteriaQuery.from(Product.class); criteriaQuery.select(root);/*from ww w . j a v a 2s .co m*/ Predicate restrictions = criteriaBuilder.conjunction(); if (productCategory != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory), criteriaBuilder.like(root.get("productCategory").<String>get("treePath"), "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId() + ProductCategory.TREE_PATH_SEPARATOR + "%"))); } if (brand != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand)); } if (promotion != null) { Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot1 = subquery1.from(Product.class); subquery1.select(subqueryRoot1); subquery1.where(criteriaBuilder.equal(subqueryRoot1, root), criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion)); Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot2 = subquery2.from(Product.class); subquery2.select(subqueryRoot2); subquery2.where(criteriaBuilder.equal(subqueryRoot2, root), criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion)); Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot3 = subquery3.from(Product.class); subquery3.select(subqueryRoot3); subquery3.where(criteriaBuilder.equal(subqueryRoot3, root), criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1), criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3))); } if (tags != null && !tags.isEmpty()) { Subquery<Product> subquery = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot = subquery.from(Product.class); subquery.select(subqueryRoot); subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery)); } if (attributeValue != null) { for (Entry<Attribute, String> entry : attributeValue.entrySet()) { String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX + entry.getKey().getPropertyIndex(); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get(propertyName), entry.getValue())); } } if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) { BigDecimal temp = startPrice; startPrice = endPrice; endPrice = temp; } if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("price"), startPrice)); } if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("price"), endPrice)); } if (isMarketable != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isMarketable"), isMarketable)); } if (isList != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList)); } if (isTop != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop)); } if (isGift != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift)); } Path<Integer> stock = root.get("stock"); Path<Integer> allocatedStock = root.get("allocatedStock"); if (isOutOfStock != null) { if (isOutOfStock) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock), criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock)); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock, allocatedStock))); } } if (isStockAlert != null) { Setting setting = SettingUtils.get(); if (isStockAlert) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock), criteriaBuilder.lessThanOrEqualTo(stock, criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock, criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())))); } } criteriaQuery.where(restrictions); List<Order> orders = pageable.getOrders(); if (orderType == OrderType.priceAsc) { orders.add(Order.asc("price")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.priceDesc) { orders.add(Order.desc("price")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.salesDesc) { orders.add(Order.desc("sales")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.scoreDesc) { orders.add(Order.desc("score")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.dateDesc) { orders.add(Order.desc("createDate")); } else { orders.add(Order.desc("isTop")); orders.add(Order.desc("modifyDate")); } return super.findPage(criteriaQuery, pageable); }
From source file:gov.guilin.dao.impl.ProductDaoImpl.java
public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags, Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert, OrderType orderType, Pageable pageable, Set<Supplier> suppliers) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class); Root<Product> root = criteriaQuery.from(Product.class); criteriaQuery.select(root);/*from w w w. j av a 2s . c o m*/ Predicate restrictions = criteriaBuilder.conjunction(); if (productCategory != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory), criteriaBuilder.like(root.get("productCategory").<String>get("treePath"), "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId() + ProductCategory.TREE_PATH_SEPARATOR + "%"))); } if (brand != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand)); } if (promotion != null) { Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot1 = subquery1.from(Product.class); subquery1.select(subqueryRoot1); subquery1.where(criteriaBuilder.equal(subqueryRoot1, root), criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion)); Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot2 = subquery2.from(Product.class); subquery2.select(subqueryRoot2); subquery2.where(criteriaBuilder.equal(subqueryRoot2, root), criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion)); Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot3 = subquery3.from(Product.class); subquery3.select(subqueryRoot3); subquery3.where(criteriaBuilder.equal(subqueryRoot3, root), criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1), criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3))); } if (tags != null && !tags.isEmpty()) { Subquery<Product> subquery = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot = subquery.from(Product.class); subquery.select(subqueryRoot); subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery)); } if (attributeValue != null) { for (Entry<Attribute, String> entry : attributeValue.entrySet()) { String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX + entry.getKey().getPropertyIndex(); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get(propertyName), entry.getValue())); } } if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) { BigDecimal temp = startPrice; startPrice = endPrice; endPrice = temp; } if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("price"), startPrice)); } if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("price"), endPrice)); } if (isMarketable != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isMarketable"), isMarketable)); } if (isList != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList)); } if (isTop != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop)); } if (isGift != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift)); } Path<Integer> stock = root.get("stock"); Path<Integer> allocatedStock = root.get("allocatedStock"); if (isOutOfStock != null) { if (isOutOfStock) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock), criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock)); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock, allocatedStock))); } } if (isStockAlert != null) { Setting setting = SettingUtils.get(); if (isStockAlert) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock), criteriaBuilder.lessThanOrEqualTo(stock, criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock, criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())))); } } //??ADDbyDanielChen 20140502 if ((suppliers != null) && !(suppliers.isEmpty())) { Expression<Supplier> exp = root.get("supplier"); restrictions = criteriaBuilder.and(restrictions, exp.in(suppliers)); } criteriaQuery.where(restrictions); List<Order> orders = pageable.getOrders(); if (orderType == OrderType.priceAsc) { orders.add(Order.asc("price")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.priceDesc) { orders.add(Order.desc("price")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.salesDesc) { orders.add(Order.desc("sales")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.scoreDesc) { orders.add(Order.desc("score")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.dateDesc) { orders.add(Order.desc("createDate")); } else { orders.add(Order.desc("isTop")); orders.add(Order.desc("modifyDate")); } return super.findPage(criteriaQuery, pageable); }
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 w w w . ja v a 2 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.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected void attachActiveRestriction(Date currentDate, Path<? extends Product> product, Path<? extends Sku> sku, List<Predicate> restrictions) { CriteriaBuilder builder = em.getCriteriaBuilder(); // Add the product archived status flag restriction restrictions.add(builder.or(builder.isNull(product.get("archiveStatus").get("archived")), builder.equal(product.get("archiveStatus").get("archived"), 'N'))); // Add the active start/end date restrictions restrictions.add(builder.lessThan(sku.get("activeStartDate").as(Date.class), currentDate)); restrictions.add(builder.or(builder.isNull(sku.get("activeEndDate")), builder.greaterThan(sku.get("activeEndDate").as(Date.class), currentDate))); }
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;/* w w w .j av a2s . co 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.jasig.portal.events.aggr.JpaBaseAggregationDao.java
@Override public final void afterPropertiesSet() throws Exception { this.timeDimensionParameter = this.createParameterExpression(TimeDimension.class, "timeDimension"); this.dateDimensionParameter = this.createParameterExpression(DateDimension.class, "dateDimension"); this.intervalParameter = this.createParameterExpression(AggregationInterval.class, "interval"); this.aggregatedGroupParameter = this.createParameterExpression(AggregatedGroupMapping.class, "aggregatedGroup"); this.aggregatedGroupsParameter = this.createParameterExpression(Set.class, "aggregatedGroups"); this.startDate = this.createParameterExpression(LocalDate.class, "startDate"); this.endMinusOneDate = this.createParameterExpression(LocalDate.class, "endMinusOneDate"); this.endDate = this.createParameterExpression(LocalDate.class, "endDate"); this.startTime = this.createParameterExpression(LocalTime.class, "startTime"); this.endTime = this.createParameterExpression(LocalTime.class, "endTime"); this.createParameterExpressions(); this.findAggregationByDateTimeIntervalQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() { @Override//from www . j av a2 s . com public CriteriaQuery<T> apply(CriteriaBuilder cb) { final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType); final Root<T> ba = criteriaQuery.from(aggregationEntityType); addFetches(ba); criteriaQuery.select(ba); criteriaQuery.where( cb.equal(ba.get(BaseAggregationImpl_.dateDimension), dateDimensionParameter), cb.equal(ba.get(BaseAggregationImpl_.timeDimension), timeDimensionParameter), cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter)); return criteriaQuery; } }); this.findAggregationByDateTimeIntervalGroupQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() { @Override public CriteriaQuery<T> apply(CriteriaBuilder cb) { final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType); final Root<T> ba = criteriaQuery.from(aggregationEntityType); final List<Predicate> keyPredicates = new ArrayList<Predicate>(); keyPredicates .add(cb.equal(ba.get(BaseAggregationImpl_.dateDimension), dateDimensionParameter)); keyPredicates .add(cb.equal(ba.get(BaseAggregationImpl_.timeDimension), timeDimensionParameter)); keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter)); keyPredicates.add( cb.equal(ba.get(BaseAggregationImpl_.aggregatedGroup), aggregatedGroupParameter)); addAggregationSpecificKeyPredicate(cb, ba, keyPredicates); criteriaQuery.select(ba); criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()])); return criteriaQuery; } }); this.findAggregationsByDateRangeQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() { @Override public CriteriaQuery<T> apply(CriteriaBuilder cb) { final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType); final Root<T> ba = criteriaQuery.from(aggregationEntityType); final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension, JoinType.LEFT); final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension, JoinType.LEFT); final List<Predicate> keyPredicates = new ArrayList<Predicate>(); keyPredicates.add(cb.and( //Restrict results by outer date range cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate), cb.lessThan(dd.get(DateDimensionImpl_.date), endDate))); keyPredicates.add(cb.or( //Restrict start of range by time as well cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate), cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime))); keyPredicates.add(cb.or( //Restrict end of range by time as well cb.lessThan(dd.get(DateDimensionImpl_.date), endMinusOneDate), cb.lessThan(td.get(TimeDimensionImpl_.time), endTime))); keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter)); keyPredicates .add(ba.get(BaseAggregationImpl_.aggregatedGroup).in(aggregatedGroupsParameter)); addAggregationSpecificKeyPredicate(cb, ba, keyPredicates); criteriaQuery.select(ba); criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()])); criteriaQuery.orderBy(cb.desc(dd.get(DateDimensionImpl_.date)), cb.desc(td.get(TimeDimensionImpl_.time))); return criteriaQuery; } }); /* * Similar to the previous query but only returns aggregates that also match the unclosed predicate generated * by the subclass. This is used for finding aggregates that missed having intervalComplete called due to * interval boundary placement. */ this.findUnclosedAggregationsByDateRangeQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() { @Override public CriteriaQuery<T> apply(CriteriaBuilder cb) { final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType); final Root<T> ba = criteriaQuery.from(aggregationEntityType); final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension, JoinType.LEFT); final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension, JoinType.LEFT); addFetches(ba); final List<Predicate> keyPredicates = new ArrayList<Predicate>(); keyPredicates.add(cb.and( //Restrict results by outer date range cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate), cb.lessThan(dd.get(DateDimensionImpl_.date), endDate))); keyPredicates.add(cb.or( //Restrict start of range by time as well cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate), cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime))); keyPredicates.add(cb.or( //Restrict end of range by time as well cb.lessThan(dd.get(DateDimensionImpl_.date), endMinusOneDate), cb.lessThan(td.get(TimeDimensionImpl_.time), endTime))); keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter)); //No aggregation specific key bits here, we only have start/end/interval parameters to work with addUnclosedPredicate(cb, ba, keyPredicates); criteriaQuery.select(ba); criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()])); return criteriaQuery; } }); this.createCriteriaQueries(); }
From source file:org.jboss.pnc.datastore.predicates.rsql.RSQLNodeTravellerPredicate.java
public RSQLNodeTravellerPredicate(Class<Entity> entityClass, String rsql) throws RSQLParserException { operations.put(RSQLOperators.EQUAL, new AbstractTransformer<Entity>() { @Override/*ww w .ja v a2 s . c o m*/ Predicate transform(Root<Entity> r, Path<?> selectedPath, CriteriaBuilder cb, String operand, List<Object> convertedArguments) { return cb.equal(selectedPath, convertedArguments.get(0)); } }); operations.put(RSQLOperators.NOT_EQUAL, new AbstractTransformer<Entity>() { @Override Predicate transform(Root<Entity> r, Path<?> selectedPath, CriteriaBuilder cb, String operand, List<Object> convertedArguments) { return cb.notEqual(selectedPath, convertedArguments.get(0)); } }); operations.put(RSQLOperators.GREATER_THAN, (r, cb, clazz, operand, arguments) -> cb .greaterThan((Path) selectWithOperand(r, operand, clazz), arguments.get(0))); operations.put(RSQLOperators.GREATER_THAN_OR_EQUAL, (r, cb, clazz, operand, arguments) -> cb .greaterThanOrEqualTo((Path) selectWithOperand(r, operand, clazz), arguments.get(0))); operations.put(RSQLOperators.LESS_THAN, (r, cb, clazz, operand, arguments) -> cb .lessThan((Path) selectWithOperand(r, operand, clazz), arguments.get(0))); operations.put(RSQLOperators.LESS_THAN_OR_EQUAL, (r, cb, clazz, operand, arguments) -> cb .lessThanOrEqualTo((Path) selectWithOperand(r, operand, clazz), arguments.get(0))); operations.put(RSQLOperators.IN, (r, cb, clazz, operand, arguments) -> ((Path) selectWithOperand(r, operand, clazz)).in(arguments)); operations.put(RSQLOperators.NOT_IN, (r, cb, clazz, operand, arguments) -> cb .not(((Path) selectWithOperand(r, operand, clazz)).in(arguments))); operations.put(LIKE, (r, cb, clazz, operand, arguments) -> cb.like(cb.lower((Path) selectWithOperand(r, operand, clazz)), preprocessLikeOperatorArgument(arguments.get(0).toLowerCase()))); operations.put(IS_NULL, (r, cb, clazz, operand, arguments) -> { if (Boolean.parseBoolean(arguments.get(0))) { return cb.isNull((Path) selectWithOperand(r, operand, clazz)); } else { return cb.isNotNull((Path) selectWithOperand(r, operand, clazz)); } }); Set<ComparisonOperator> operators = RSQLOperators.defaultOperators(); operators.add(LIKE); operators.add(IS_NULL); rootNode = new RSQLParser(operators).parse(preprocessRSQL(rsql)); selectingClass = entityClass; }
From source file:org.sparkcommerce.core.catalog.dao.ProductDaoImpl.java
protected void attachProductSearchCriteria(ProductSearchCriteria 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 w w w . j av a2 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.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 .ja v a2 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(); } }; }