List of usage examples for javax.persistence.criteria CriteriaBuilder notEqual
Predicate notEqual(Expression<?> x, Object y);
From source file:net.shopxx.dao.impl.OrderDaoImpl.java
public List<Order> findList(Order.Type type, Order.Status status, Member member, Goods goods, Boolean isPendingReceive, Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint, Boolean isAllocatedStock, Boolean hasExpired, Integer count, List<Filter> filters, List<net.shopxx.Order> orders) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class); Root<Order> root = criteriaQuery.from(Order.class); criteriaQuery.select(root);// w w w .j av a2s .co m Predicate restrictions = criteriaBuilder.conjunction(); if (type != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type)); } if (status != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status)); } if (member != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member)); } if (goods != null) { Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class); Root<Product> productSubqueryRoot = productSubquery.from(Product.class); productSubquery.select(productSubqueryRoot); productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods)); Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class); Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class); orderItemSubquery.select(orderItemSubqueryRoot); orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root), criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery)); } if (isPendingReceive != null) { Predicate predicate = criteriaBuilder.and( criteriaBuilder.or(root.get("expire").isNull(), criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())), criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery), criteriaBuilder.notEqual(root.get("status"), Order.Status.completed), criteriaBuilder.notEqual(root.get("status"), Order.Status.failed), criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled), criteriaBuilder.notEqual(root.get("status"), Order.Status.denied), criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount"))); if (isPendingReceive) { restrictions = criteriaBuilder.and(restrictions, predicate); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate)); } } if (isPendingRefunds != null) { Predicate predicate = criteriaBuilder.or( criteriaBuilder.and( criteriaBuilder.or( criteriaBuilder.and(root.get("expire").isNotNull(), criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date())), criteriaBuilder.equal(root.get("status"), Order.Status.failed), criteriaBuilder.equal(root.get("status"), Order.Status.canceled), criteriaBuilder.equal(root.get("status"), Order.Status.denied)), criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)), criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed), criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")))); if (isPendingRefunds) { restrictions = criteriaBuilder.and(restrictions, predicate); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate)); } } if (isUseCouponCode != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode)); } if (isExchangePoint != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint)); } if (isAllocatedStock != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock)); } if (hasExpired != null) { if (hasExpired) { restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(), criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date())); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(), criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date()))); } } criteriaQuery.where(restrictions); return super.findList(criteriaQuery, null, count, filters, orders); }
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;// ww w.j ava 2 s. c o 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:com.sammyun.dao.impl.BaseDaoImpl.java
private void addRestrictions(CriteriaQuery<T> criteriaQuery, Pageable pageable) { if (criteriaQuery == null || pageable == null) { return;//from ww w . j a v a 2s .c o m } Root<T> root = getRoot(criteriaQuery); if (root == null) { return; } CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); Predicate restrictions = criteriaQuery.getRestriction() != null ? criteriaQuery.getRestriction() : criteriaBuilder.conjunction(); if (StringUtils.isNotEmpty(pageable.getSearchProperty()) && StringUtils.isNotEmpty(pageable.getSearchValue())) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder .like(root.<String>get(pageable.getSearchProperty()), "%" + pageable.getSearchValue() + "%")); } if (pageable.getFilters() != null) { for (Filter filter : pageable.getFilters()) { 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.pushio.webapp.support.persistence.DynamicSpecifications.java
/** * @see ??JPA/* w w w. j a va2 s. c om*/ * @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.openmeetings.data.user.UserManager.java
/** * suche eines Bentzers//from w w w . j av a2 s.co 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.finra.herd.dao.impl.AbstractHerdDao.java
/** * Builds a query restriction predicate for the storage. * * @param builder the criteria builder//from w w w . j av a 2 s .c o m * @param storageEntity the storage entity that appears in the from clause * @param storagePlatformEntity the storage platform entity that appears in the from clause * @param storageNames the list of storage names where the business object data storage units should be looked for (case-insensitive) * @param storagePlatformType the optional storage platform type, e.g. S3 for Hive DDL. It is ignored when the list of storages is not empty * @param excludedStoragePlatformType the optional storage platform type to be excluded from search. It is ignored when the list of storages is not empty or * the storage platform type is specified * * @return the query restriction predicate */ protected Predicate getQueryRestrictionOnStorage(CriteriaBuilder builder, From<?, StorageEntity> storageEntity, From<?, StoragePlatformEntity> storagePlatformEntity, List<String> storageNames, String storagePlatformType, String excludedStoragePlatformType) { List<Predicate> predicates = new ArrayList<>(); // If specified, add restriction on storage. if (!CollectionUtils.isEmpty(storageNames)) { // Add a storage name restriction to the main query where clause. List<String> uppercaseStorageNames = new ArrayList<>(); for (String storageName : storageNames) { uppercaseStorageNames.add(storageName.toUpperCase()); } predicates.add(builder.upper(storageEntity.get(StorageEntity_.name)).in(uppercaseStorageNames)); } else if (StringUtils.isNotBlank(storagePlatformType)) { // Select storage units only from the storages of the specified storage platform type. predicates.add( builder.equal(storagePlatformEntity.get(StoragePlatformEntity_.name), storagePlatformType)); } else if (StringUtils.isNotBlank(excludedStoragePlatformType)) { // Ignore any storages of the excluded storage platform type. predicates.add(builder.notEqual(storagePlatformEntity.get(StoragePlatformEntity_.name), excludedStoragePlatformType)); } return builder.and(predicates.toArray(new Predicate[predicates.size()])); }
From source file:org.finra.herd.dao.impl.HerdDaoImpl.java
/** * Retrieves a list of storage unit entities per specified parameters. This method processes a sublist of partition filters specified by * partitionFilterSubListFromIndex and partitionFilterSubListSize parameters. * * @param businessObjectFormatKey the business object format key (case-insensitive). If a business object format version isn't specified, the latest * available format version for each partition value will be used * @param partitionFilters the list of partition filter to be used to select business object data instances. Each partition filter contains a list of * primary and sub-partition values in the right order up to the maximum partition levels allowed by business object data registration - with partition * values for the relative partitions not to be used for selection passed as nulls * @param businessObjectDataVersion the business object data version. If a business object data version isn't specified, the latest data version based on * the specified business object data status is returned * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified. When * business object data version and business object data status both are not specified, the latest data version for each set of partition values will be * used regardless of the status/* www. j a va2s. c o m*/ * @param storageNames the list of storage names where the business object data storage units should be looked for (case-insensitive) * @param storagePlatformType the optional storage platform type, e.g. S3 for Hive DDL. It is ignored when the list of storages is not empty * @param excludedStoragePlatformType the optional storage platform type to be excluded from search. It is ignored when the list of storages is not empty or * the storage platform type is specified * @param partitionFilterSubListFromIndex the index of the first element in the partition filter sublist * @param partitionFilterSubListSize the size of the partition filter sublist * @param selectOnlyAvailableStorageUnits specifies if only available storage units will be selected or any storage units regardless of their status * * @return the list of storage unit entities sorted by partition values */ private List<StorageUnitEntity> getStorageUnitsByPartitionFiltersAndStorages( BusinessObjectFormatKey businessObjectFormatKey, List<List<String>> partitionFilters, Integer businessObjectDataVersion, String businessObjectDataStatus, List<String> storageNames, String storagePlatformType, String excludedStoragePlatformType, boolean selectOnlyAvailableStorageUnits, int partitionFilterSubListFromIndex, int partitionFilterSubListSize) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> criteria = builder.createTupleQuery(); // The criteria root is the storage unit. Root<StorageUnitEntity> storageUnitEntity = criteria.from(StorageUnitEntity.class); // Join to the other tables we can filter on. Join<StorageUnitEntity, BusinessObjectDataEntity> businessObjectDataEntity = storageUnitEntity .join(StorageUnitEntity_.businessObjectData); Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage); Join<StorageEntity, StoragePlatformEntity> storagePlatformEntity = storageEntity .join(StorageEntity_.storagePlatform); Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity .join(BusinessObjectDataEntity_.businessObjectFormat); Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity .join(BusinessObjectFormatEntity_.fileType); Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity .join(BusinessObjectFormatEntity_.businessObjectDefinition); Join<StorageUnitEntity, StorageUnitStatusEntity> storageUnitStatusEntity = storageUnitEntity .join(StorageUnitEntity_.status); // Create the standard restrictions (i.e. the standard where clauses). // Create a standard restriction based on the business object format key values. // Please note that we specify not to ignore the business object format version. Predicate mainQueryRestriction = getQueryRestriction(builder, businessObjectFormatEntity, fileTypeEntity, businessObjectDefinitionEntity, businessObjectFormatKey, false); // If a format version was not specified, use the latest available for this set of partition values. if (businessObjectFormatKey.getBusinessObjectFormatVersion() == null) { // Get the latest available format version for this set of partition values and per other restrictions. Subquery<Integer> subQuery = getMaximumBusinessObjectFormatVersionSubQuery(builder, criteria, businessObjectDefinitionEntity, businessObjectFormatEntity, fileTypeEntity, businessObjectDataEntity, businessObjectDataVersion, businessObjectDataStatus, storageEntity, selectOnlyAvailableStorageUnits); mainQueryRestriction = builder.and(mainQueryRestriction, builder.in( businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion)) .value(subQuery)); } // Add restriction as per specified primary and/or sub-partition values. mainQueryRestriction = builder.and(mainQueryRestriction, getQueryRestrictionOnPartitionValues(builder, businessObjectDataEntity, partitionFilters.subList(partitionFilterSubListFromIndex, partitionFilterSubListFromIndex + partitionFilterSubListSize))); // If a data version was specified, use it. Otherwise, use the latest one as per specified business object data status. if (businessObjectDataVersion != null) { mainQueryRestriction = builder.and(mainQueryRestriction, builder.equal( businessObjectDataEntity.get(BusinessObjectDataEntity_.version), businessObjectDataVersion)); } else { // Business object data version is not specified, so get the latest one as per specified business object data status, if any. // Meaning, when both business object data version and business object data status are not specified, we just return // the latest business object data version in the specified storage. Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria, businessObjectDataEntity, businessObjectFormatEntity, businessObjectDataStatus, storageEntity); mainQueryRestriction = builder.and(mainQueryRestriction, builder.in(businessObjectDataEntity.get(BusinessObjectDataEntity_.version)).value(subQuery)); } // If specified, add restriction on storage. if (!CollectionUtils.isEmpty(storageNames)) { // Add a storage name restriction to the main query where clause. List<String> uppercaseStorageNames = new ArrayList<>(); for (String storageName : storageNames) { uppercaseStorageNames.add(storageName.toUpperCase()); } mainQueryRestriction = builder.and(mainQueryRestriction, builder.upper(storageEntity.get(StorageEntity_.name)).in(uppercaseStorageNames)); } else if (StringUtils.isNotBlank(storagePlatformType)) { // Select storage units only from the storages of the specified storage platform type. mainQueryRestriction = builder.and(mainQueryRestriction, builder.equal(storagePlatformEntity.get(StoragePlatformEntity_.name), storagePlatformType)); } else if (StringUtils.isNotBlank(excludedStoragePlatformType)) { // Ignore any storages of the excluded storage platform type. mainQueryRestriction = builder.and(mainQueryRestriction, builder .notEqual(storagePlatformEntity.get(StoragePlatformEntity_.name), excludedStoragePlatformType)); } // If specified, add a restriction on storage unit status availability flag. if (selectOnlyAvailableStorageUnits) { mainQueryRestriction = builder.and(mainQueryRestriction, builder.isTrue(storageUnitStatusEntity.get(StorageUnitStatusEntity_.available))); } // Order by partitions and storage names. List<Order> orderBy = new ArrayList<>(); for (SingularAttribute<BusinessObjectDataEntity, String> businessObjectDataPartition : BUSINESS_OBJECT_DATA_PARTITIONS) { orderBy.add(builder.asc(businessObjectDataEntity.get(businessObjectDataPartition))); } orderBy.add(builder.asc(storageEntity.get(StorageEntity_.name))); // Add the clauses for the query. // Please note that we use multiselect here in order to eliminate the Hibernate N+1 SELECT's problem, // happening when we select storage unit entities and access their relative business object data entities. // This is an alternative approach, since adding @Fetch(FetchMode.JOIN) failed to address the issue. criteria.multiselect(storageUnitEntity, storageUnitStatusEntity, storageEntity, storagePlatformEntity, businessObjectDataEntity, businessObjectFormatEntity).where(mainQueryRestriction).orderBy(orderBy); // Run the query to get a list of tuples back. List<Tuple> tuples = entityManager.createQuery(criteria).getResultList(); // Build a list of storage unit entities to return. List<StorageUnitEntity> storageUnitEntities = new ArrayList<>(); for (Tuple tuple : tuples) { storageUnitEntities.add(tuple.get(storageUnitEntity)); } return storageUnitEntities; }
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()); }/*w w w.ja v a 2s . c om*/ 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.jboss.pnc.datastore.predicates.rsql.RSQLNodeTravellerPredicate.java
public RSQLNodeTravellerPredicate(Class<Entity> entityClass, String rsql) throws RSQLParserException { operations.put(RSQLOperators.EQUAL, new AbstractTransformer<Entity>() { @Override/*www . ja v a2s . 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.seedstack.i18n.rest.internal.KeyJpaFinder.java
/** * Extracts predicates from criteria./*from w w w . jav a 2 s .c o m*/ * * @param criteria criteria * @param cb criteria builder * @param k root key * @return list of predicate */ private Predicate[] getPredicates(Map<String, Object> criteria, CriteriaQuery q, CriteriaBuilder cb, Root<Key> k) { List<Predicate> predicates = new ArrayList<Predicate>(); if (criteria != null) { // extract criteria from the map Boolean isApprox = (Boolean) criteria.get(IS_APPROX); Boolean isMissing = (Boolean) criteria.get(IS_MISSING); Boolean isOutdated = (Boolean) criteria.get(IS_OUTDATED); String searchName = (String) criteria.get(SEARCH_NAME); // is the key LIKE searchName if (StringUtils.isNotBlank(searchName)) { predicates.add(cb.like(k.<String>get(ENTITY_ID), "%" + searchName + "%")); } // is the key outdated if (isOutdated != null) { predicates.add(cb.equal(k.<Boolean>get(OUTDATED), isOutdated)); } // if a default translation is available String defaultLocale = localeService.getDefaultLocale(); if (defaultLocale != null && isApprox != null) { // join translation table Join<Key, Translation> tln = k.join(TRANSLATIONS, JoinType.LEFT); // WHERE locale = default locale predicates.add(cb.equal(tln.get(ENTITY_ID).get(LOCALE), defaultLocale)); // is the translation approximate predicates.add(cb.equal(tln.get(APPROXIMATE), isApprox)); } // is the translation missing if (isMissing != null) { // SubQuery to find all the key which get a translation for the default locale //noinspection unchecked Subquery<String> subquery = q.subquery(String.class); Root<Key> fromKey = subquery.from(Key.class); subquery.select(fromKey.<String>get(ENTITY_ID)); Join join = fromKey.join(TRANSLATIONS, JoinType.LEFT); subquery.where(cb.and(cb.equal(join.get(ENTITY_ID).get(LOCALE), defaultLocale), cb.notEqual(join.get(VALUE), ""))); // Find all keys not in the above subquery, ie. all the keys missing predicates.add(cb.not(cb.in(k.get(ENTITY_ID)).value(subquery))); } } return predicates.toArray(new Predicate[predicates.size()]); }