List of usage examples for javax.persistence.criteria CriteriaBuilder isNull
Predicate isNull(Expression<?> x);
From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java
/** * @see ??JPA//w ww .j av a 2 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:nl.b3p.viewer.stripes.ApplicationActionBean.java
static Application findApplication(String name, String version) { EntityManager em = Stripersist.getEntityManager(); if (name != null) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery q = cb.createQuery(Application.class); Root<Application> root = q.from(Application.class); Predicate namePredicate = cb.equal(root.get("name"), name); Predicate versionPredicate = version != null ? cb.equal(root.get("version"), version) : cb.isNull(root.get("version")); q.where(cb.and(namePredicate, versionPredicate)); try {/*from w w w. j a va 2 s . c om*/ return (Application) em.createQuery(q).getSingleResult(); } catch (NoResultException nre) { String decodedName = StringUtil.urlDecode(name); if (!decodedName.equals(name)) { return findApplication(decodedName, version); } } } return null; }
From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java
@SuppressWarnings("unchecked") public <T extends IBean> T[] findByValue(Class<T> beansInterface, String name, Object value, String orderBy, boolean ascending) { // validate entity manager transaction if (entityManager == null) { throw new IllegalStateException("Transaction not initiated or already closed"); }//from ww w . jav a 2s . c om // validate bean interface Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface); if (beanClass == null) { throw new IllegalArgumentException("Invalid bean interface specified"); } // get persistent beans by criteria try { // construct query criteria CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass); Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass); if (name != null) { criteriaQuery.where((value != null) ? criteriaBuilder.equal(beanRoot.get(name), value) : criteriaBuilder.isNull(beanRoot.get(name))); } if (orderBy != null) { criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy)) : criteriaBuilder.desc(beanRoot.get(orderBy))); } // invoke query Query query = entityManager.createQuery(criteriaQuery); List<? extends IBean> beansList = query.getResultList(); if ((beansList != null) && !beansList.isEmpty()) { return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size())); } } catch (Exception e) { logger.error("Unexpected exception: " + e, e); } return (T[]) Array.newInstance(beansInterface, 0); }
From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java
@SuppressWarnings("unchecked") public <T extends IBean> T[] findByValues(Class<T> beansInterface, Map<String, Object> values, String orderBy, boolean ascending) { // validate entity manager transaction if (entityManager == null) { throw new IllegalStateException("Transaction not initiated or already closed"); }/*from w w w .j a va 2s.c om*/ // validate bean interface Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface); if (beanClass == null) { throw new IllegalArgumentException("Invalid bean interface specified"); } // get persistent beans by criteria try { // construct query criteria CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass); Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass); if ((values != null) && !values.isEmpty()) { Predicate predicate = null; for (Map.Entry<String, Object> value : values.entrySet()) { Predicate valuePredicate = ((value.getValue() != null) ? criteriaBuilder.equal(beanRoot.get(value.getKey()), value.getValue()) : criteriaBuilder.isNull(beanRoot.get(value.getKey()))); predicate = ((predicate != null) ? criteriaBuilder.and(predicate, valuePredicate) : valuePredicate); } criteriaQuery.where(predicate); } if (orderBy != null) { criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy)) : criteriaBuilder.desc(beanRoot.get(orderBy))); } // invoke query Query query = entityManager.createQuery(criteriaQuery); List<? extends IBean> beansList = query.getResultList(); if ((beansList != null) && !beansList.isEmpty()) { return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size())); } } catch (Exception e) { logger.error("Unexpected exception: " + e, e); } return (T[]) Array.newInstance(beansInterface, 0); }
From source file:org.broadleafcommerce.admin.server.service.handler.SkuRestrictionFactoryImpl.java
@Override public Restriction getRestriction(final String type, String propertyId) { final Restriction delegateRestriction = delegate.getRestriction(type, propertyId); return new Restriction().withFilterValueConverter(delegateRestriction.getFilterValueConverter()) .withPredicateProvider(new PredicateProvider() { @Override//w ww. j a v a 2 s . c o m public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root, String ceilingEntity, String fullPropertyName, Path explicitPath, List directValues) { FieldPath fieldPath = fieldPathBuilder.getFieldPath(root, fullPropertyName); if ((StringUtils.isNotEmpty(skuPropertyPrefix) && fullPropertyName.startsWith(skuPropertyPrefix)) || CollectionUtils.isEmpty(fieldPath.getAssociationPath())) { Path targetPropertyPath = fieldPathBuilder.getPath(root, fieldPath, builder); Path defaultSkuPropertyPath = fieldPathBuilder.getPath(root, DEFAULT_SKU_PATH_PREFIX + fullPropertyName, builder); Path productPath = fieldPathBuilder.getPath(root, "product", builder); Predicate propertyExpression; Predicate defaultSkuExpression; if (delegateRestriction.getPredicateProvider() instanceof LikePredicateProvider) { propertyExpression = builder.like(builder.lower(targetPropertyPath), ((String) directValues.get(0)).toLowerCase()); defaultSkuExpression = builder.like(builder.lower(defaultSkuPropertyPath), ((String) directValues.get(0)).toLowerCase()); } else if (delegateRestriction .getPredicateProvider() instanceof IsNullPredicateProvider) { propertyExpression = builder.isNull(targetPropertyPath); defaultSkuExpression = builder.isNull(defaultSkuPropertyPath); } else if (delegateRestriction .getPredicateProvider() instanceof BetweenDatePredicateProvider) { if (directValues.size() == 2) { if (directValues.get(0) == null) { propertyExpression = builder.lessThan(targetPropertyPath, (Comparable) directValues.get(1)); defaultSkuExpression = builder.lessThan(defaultSkuPropertyPath, (Comparable) directValues.get(1)); } else if (directValues.get(1) == null) { propertyExpression = builder.greaterThanOrEqualTo(targetPropertyPath, (Comparable) directValues.get(0)); defaultSkuExpression = builder.greaterThanOrEqualTo(defaultSkuPropertyPath, (Comparable) directValues.get(0)); } else { propertyExpression = builder.between(targetPropertyPath, (Comparable) directValues.get(0), (Comparable) directValues.get(1)); defaultSkuExpression = builder.between(defaultSkuPropertyPath, (Comparable) directValues.get(0), (Comparable) directValues.get(1)); } } else { propertyExpression = builder.equal(targetPropertyPath, directValues.get(0)); defaultSkuExpression = builder.equal(defaultSkuPropertyPath, directValues.get(0)); } } else if (delegateRestriction .getPredicateProvider() instanceof BetweenPredicateProvider) { if (directValues.size() > 1) { propertyExpression = builder.between(targetPropertyPath, (Comparable) directValues.get(0), (Comparable) directValues.get(1)); defaultSkuExpression = builder.between(defaultSkuPropertyPath, (Comparable) directValues.get(0), (Comparable) directValues.get(1)); } else { propertyExpression = builder.equal(targetPropertyPath, directValues.get(0)); defaultSkuExpression = builder.equal(defaultSkuPropertyPath, directValues.get(0)); } } else if (delegateRestriction .getPredicateProvider() instanceof CollectionSizeEqualPredicateProvider) { propertyExpression = builder.equal(builder.size(targetPropertyPath), directValues.get(0)); defaultSkuExpression = builder.equal(builder.size(defaultSkuPropertyPath), directValues.get(0)); } else if (delegateRestriction.getPredicateProvider() instanceof EqPredicateProvider) { propertyExpression = builder.equal(targetPropertyPath, directValues.get(0)); defaultSkuExpression = builder.equal(defaultSkuPropertyPath, directValues.get(0)); } else { throw new IllegalArgumentException("Unknown PredicateProvider instance: " + delegateRestriction.getPredicateProvider().getClass().getName()); } return buildCompositePredicate(builder, targetPropertyPath, productPath, propertyExpression, defaultSkuExpression); } return delegateRestriction.getPredicateProvider().buildPredicate(builder, fieldPathBuilder, root, ceilingEntity, fullPropertyName, explicitPath, directValues); } }); }
From source file:org.broadleafcommerce.admin.server.service.handler.SkuRestrictionFactoryImpl.java
protected Predicate buildCompositePredicate(CriteriaBuilder builder, Path targetPropertyPath, Path productPath, Predicate propertyExpression, Predicate defaultSkuExpression) { return builder.or( builder.or(builder.and(builder.isNotNull(targetPropertyPath), propertyExpression), builder.and(builder.and(builder.isNull(targetPropertyPath), builder.isNotNull(productPath)), defaultSkuExpression)), builder.and(builder.isNull(productPath), propertyExpression)); }
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.openadmin.server.service.persistence.ArchiveStatusPersistenceEventHandler.java
@Override public PersistenceManagerEventHandlerResponse preFetch(PersistenceManager persistenceManager, PersistencePackage persistencePackage, CriteriaTransferObject cto) throws ServiceException { try {//from w w w. j av a2 s. co m Class<?>[] entityClasses = persistenceManager.getDynamicEntityDao() .getAllPolymorphicEntitiesFromCeiling( Class.forName(persistencePackage.getCeilingEntityFullyQualifiedClassname())); AtomicBoolean isArchivable = new AtomicBoolean(false); for (Class<?> entity : entityClasses) { AtomicBoolean test = new AtomicBoolean(true); extensionManager.getProxy().isArchivable(entity, test); if (!test.get()) { isArchivable.set(false); break; } if (Status.class.isAssignableFrom(entity)) { isArchivable.set(true); } } if (isArchivable.get() && !persistencePackage.getPersistencePerspective().getShowArchivedFields()) { String targetPropertyName = "archiveStatus.archived"; if (persistencePackage.getPersistencePerspectiveItems() .containsKey(PersistencePerspectiveItemType.ADORNEDTARGETLIST)) { AdornedTargetList atl = (AdornedTargetList) persistencePackage.getPersistencePerspectiveItems() .get(PersistencePerspectiveItemType.ADORNEDTARGETLIST); targetPropertyName = atl.getTargetObjectPath() + "." + targetPropertyName; } FilterMapping filterMapping = new FilterMapping() .withFieldPath(new FieldPath().withTargetProperty(targetPropertyName)) .withDirectFilterValues(new EmptyFilterValues()).withRestriction(new Restriction() .withPredicateProvider(new PredicateProvider<Character, Character>() { @Override public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root, String ceilingEntity, String fullPropertyName, Path<Character> explicitPath, List<Character> directValues) { return builder.or(builder.equal(explicitPath, 'N'), builder.isNull(explicitPath)); } })); cto.getAdditionalFilterMappings().add(filterMapping); } return new PersistenceManagerEventHandlerResponse().withStatus( PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus.HANDLED); } catch (ClassNotFoundException e) { LOG.error("Could not find the class " + persistencePackage.getCeilingEntityFullyQualifiedClassname() + " to " + "compute polymorphic entity types for. Assuming that the entity is not archivable"); return new PersistenceManagerEventHandlerResponse().withStatus( PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus.NOT_HANDLED); } }
From source file:org.fao.geonet.repository.HarvesterSettingRepositoryOverridesImpl.java
@Override public List<HarvesterSetting> findRoots() { CriteriaBuilder criteriaBuilder = _entityManager.getCriteriaBuilder(); CriteriaQuery<HarvesterSetting> query = criteriaBuilder.createQuery(HarvesterSetting.class); Root<HarvesterSetting> root = query.from(HarvesterSetting.class); query.where(criteriaBuilder.isNull(root.get(HarvesterSetting_.parent))); return _entityManager.createQuery(query).getResultList(); }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}//w w w . ja va 2 s. c o m */ @Override public Integer getBusinessObjectDataMaxVersion(BusinessObjectDataKey businessObjectDataKey) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Integer> criteria = builder.createQuery(Integer.class); // The criteria root is the business object data. Root<BusinessObjectDataEntity> businessObjectDataEntity = criteria.from(BusinessObjectDataEntity.class); // Join to the other tables we can filter on. 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<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity .join(BusinessObjectDefinitionEntity_.namespace); // Create the path. Expression<Integer> maxBusinessObjectDataVersion = builder .max(businessObjectDataEntity.get(BusinessObjectDataEntity_.version)); // Create the standard restrictions (i.e. the standard where clauses). Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), businessObjectDataKey.getNamespace().toUpperCase()); queryRestriction = builder.and(queryRestriction, builder.equal( builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)), businessObjectDataKey.getBusinessObjectDefinitionName().toUpperCase())); queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)), businessObjectDataKey.getBusinessObjectFormatUsage().toUpperCase())); queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)), businessObjectDataKey.getBusinessObjectFormatFileType().toUpperCase())); queryRestriction = builder.and(queryRestriction, builder.equal( businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion), businessObjectDataKey.getBusinessObjectFormatVersion())); queryRestriction = builder.and(queryRestriction, builder.equal(businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue), businessObjectDataKey.getPartitionValue())); for (int i = 0; i < BusinessObjectDataEntity.MAX_SUBPARTITIONS; i++) { queryRestriction = builder.and(queryRestriction, i < businessObjectDataKey.getSubPartitionValues().size() ? builder.equal(businessObjectDataEntity.get(BUSINESS_OBJECT_DATA_SUBPARTITIONS.get(i)), businessObjectDataKey.getSubPartitionValues().get(i)) : builder.isNull( businessObjectDataEntity.get(BUSINESS_OBJECT_DATA_SUBPARTITIONS.get(i)))); } criteria.select(maxBusinessObjectDataVersion).where(queryRestriction); return entityManager.createQuery(criteria).getSingleResult(); }