List of usage examples for javax.persistence.criteria CriteriaBuilder or
Predicate or(Expression<Boolean> x, Expression<Boolean> y);
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 List<Product> readFilteredActiveProductsByQueryInternal(String query, Date currentDate, SearchCriteria searchCriteria) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); // The root of our search is Product since we are searching Root<ProductImpl> product = criteria.from(ProductImpl.class); // We also want to filter on attributes from sku and productAttributes Join<Product, Sku> sku = product.join("defaultSku"); // Product objects are what we want back criteria.select(product);//from w w w . j a v a 2s.com // We only want results that match the search query List<Predicate> restrictions = new ArrayList<Predicate>(); String lq = query.toLowerCase(); restrictions.add(builder.or(builder.like(builder.lower(sku.get("name").as(String.class)), '%' + lq + '%'), builder.like(builder.lower(sku.get("longDescription").as(String.class)), '%' + lq + '%'))); attachSearchCriteria(searchCriteria, product, sku, restrictions); attachActiveRestriction(currentDate, product, sku, restrictions); attachOrderBy(searchCriteria, product, sku, criteria); // Execute the query with the restrictions criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Product> typedQuery = em.createQuery(criteria); //don't cache - not really practical for open ended search return typedQuery.getResultList(); }
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 {//w w w. j a v a 2 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.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java
private Predicate buildPredicateFilter(CriteriaBuilder cb, Join<Connection, Profile> receiver, Root<Connection> connection) { Predicate predicate = null;// w w w. j ava 2 s .c om // owner if (this.owner != null) { predicate = cb.equal(connection.get(Connection_.senderId), owner.getId()); } // status if (this.status != null) { predicate = cb.and(predicate, cb.equal(connection.get(Connection_.status), this.status)); } Predicate pFilter = null; if (profileFilter != null) { String inputName = addPercentToStringInput(profileFilter.getName()).replace(ASTERISK_STR, SPACE_STR); String position = addPercentToStringInput(StringEscapeUtils.escapeHtml(profileFilter.getPosition())); String skills = addPercentToStringInput(StringEscapeUtils.escapeHtml(profileFilter.getSkills())); String company = addPercentToStringInput(StringEscapeUtils.escapeHtml(profileFilter.getCompany())); // if (!inputName.isEmpty()) { Predicate pName = cb.like(receiver.get(Profile_.fullName), inputName); pName = cb.or(pName, cb.like(receiver.get(Profile_.firstName), inputName)); pFilter = cb.or(pName, cb.like(receiver.get(Profile_.lastName), inputName)); } // if (!position.isEmpty()) { pFilter = appendPredicate(cb, pFilter, cb.like(receiver.get(Profile_.positions), position)); } // if (!skills.isEmpty()) { pFilter = appendPredicate(cb, pFilter, cb.like(receiver.get(Profile_.skills), skills)); } if (!company.isEmpty()) { pFilter = appendPredicate(cb, pFilter, cb.like(receiver.get(Profile_.organizations), company)); } String all = profileFilter.getAll(); if (all != null && !all.trim().isEmpty()) { all = escapeSpecialCharacter(all.trim()).toLowerCase(); Predicate pAll = cb.like(receiver.get(Profile_.fullName), all); pAll = cb.or(pAll, cb.like(receiver.get(Profile_.firstName), all)); pAll = cb.or(pAll, cb.like(receiver.get(Profile_.lastName), all)); pAll = cb.or(pAll, cb.like(receiver.get(Profile_.skills), all)); pAll = cb.or(pAll, cb.like(receiver.get(Profile_.positions), all)); pAll = cb.or(pAll, cb.like(receiver.get(Profile_.organizations), all)); pAll = cb.or(pAll, cb.like(receiver.get(Profile_.jobsDescription), all)); // pFilter = appendPredicate(cb, pFilter, pAll); } } // return appendPredicate(cb, predicate, pFilter); }
From source file:org.finra.dm.dao.impl.BaseJpaDaoImpl.java
/** * Gets an "in" clause predicate for a list of values. This will take care of breaking the list of values into a group of sub-lists where each sub-list is * placed in a separate "in" clause and all "in" clauses are "or"ed together. The size of each sub-list is obtained through an environment configuration. * * @param builder the criteria builder.//from w ww . j av a 2s . co m * @param path the path to the field that is being filtered. * @param values the list of values to place in the in clause. * @param <T> the type referenced by the path. * * @return the predicate for the in clause. */ protected <T> Predicate getPredicateForInClause(CriteriaBuilder builder, Path<T> path, List<T> values) { // Get the chunk size from the environment and use a default as necessary. int inClauseChunkSize = configurationHelper.getProperty(ConfigurationValue.DB_IN_CLAUSE_CHUNK_SIZE, Integer.class); // Initializes the returned predicate and the value list size. Predicate predicate = null; int listSize = values.size(); // Loop through each chunk of values until we have reached the end of the values. for (int i = 0; i < listSize; i += inClauseChunkSize) { // Get a sub-list for the current chunk of data. List<T> valuesSubList = values.subList(i, (listSize > (i + inClauseChunkSize) ? (i + inClauseChunkSize) : listSize)); // Get an updated predicate which will be the "in" clause of the sub-list on the first loop or the "in" clause of the sub-list "or"ed with the\ // previous sub-list "in" clause. predicate = (predicate == null ? path.in(valuesSubList) : builder.or(predicate, path.in(valuesSubList))); } // Return the "in" clause predicate. return predicate; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * Builds a query restriction predicate for the sub-query business object data entity as per partition values from the specified main query business object * data entity./* w ww . j a va 2 s . c o m*/ * * @param builder the criteria builder * @param subBusinessObjectDataEntity the sub-query business object data entity that appears in the from clause * @param mainBusinessObjectDataEntity the main query business object data entity that appears in the from clause * * @return the query restriction predicate */ private Predicate getQueryRestrictionOnPartitionValues(CriteriaBuilder builder, From<?, BusinessObjectDataEntity> subBusinessObjectDataEntity, From<?, BusinessObjectDataEntity> mainBusinessObjectDataEntity) { // Create a standard restriction on primary partition value. Predicate predicate = builder.equal( subBusinessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue), mainBusinessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue)); // Create and add standard restrictions on sub-partition values. Please note that the subpartition value columns are nullable. for (SingularAttribute<BusinessObjectDataEntity, String> businessObjectDataPartitionValueSingularAttribute : BUSINESS_OBJECT_DATA_SUBPARTITIONS) { predicate = builder.and(predicate, builder.or( builder.and( builder.isNull(subBusinessObjectDataEntity .get(businessObjectDataPartitionValueSingularAttribute)), builder.isNull(mainBusinessObjectDataEntity .get(businessObjectDataPartitionValueSingularAttribute))), builder.equal( subBusinessObjectDataEntity.get(businessObjectDataPartitionValueSingularAttribute), mainBusinessObjectDataEntity.get(businessObjectDataPartitionValueSingularAttribute)))); } return predicate; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * Builds a query restriction predicate for the sub-query business object data entity as per partition values from the specified main query business object * data entity.//from www . j a va2s .c o m * * @param builder the criteria builder * @param businessObjectDataEntity the business object data entity that appears in the from clause * @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. * * @return the query restriction predicate */ private Predicate getQueryRestrictionOnPartitionValues(CriteriaBuilder builder, From<?, BusinessObjectDataEntity> businessObjectDataEntity, List<List<String>> partitionFilters) { // Create a query restriction as per specified primary and/or sub-partition values. Predicate predicate = null; for (List<String> partitionFilter : partitionFilters) { // Add restriction for each partition level if the relative partition value is specified in the partition filter. Predicate partitionRestriction = null; for (int partitionLevel = 0; partitionLevel < BusinessObjectDataEntity.MAX_SUBPARTITIONS + 1; partitionLevel++) { String partitionValue = partitionFilter.get(partitionLevel); if (StringUtils.isNotBlank(partitionValue)) { Predicate partitionValueRestriction = builder.equal( businessObjectDataEntity.get(BUSINESS_OBJECT_DATA_PARTITIONS.get(partitionLevel)), partitionValue); partitionRestriction = (partitionRestriction == null ? partitionValueRestriction : builder.and(partitionRestriction, partitionValueRestriction)); } } predicate = (predicate == null ? partitionRestriction : builder.or(predicate, partitionRestriction)); } return predicate; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}//from w w w. j av a 2 s . co m */ @Override public List<BusinessObjectDataNotificationRegistrationEntity> getBusinessObjectDataNotificationRegistrations( String notificationEventTypeCode, BusinessObjectDataKey businessObjectDataKey) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<BusinessObjectDataNotificationRegistrationEntity> criteria = builder .createQuery(BusinessObjectDataNotificationRegistrationEntity.class); // The criteria root is the business object data notification registration entity. Root<BusinessObjectDataNotificationRegistrationEntity> businessObjectDataNotificationEntity = criteria .from(BusinessObjectDataNotificationRegistrationEntity.class); // Join to the other tables we can filter on. Join<BusinessObjectDataNotificationRegistrationEntity, NamespaceEntity> namespaceEntity = businessObjectDataNotificationEntity .join(BusinessObjectDataNotificationRegistrationEntity_.namespace); Join<BusinessObjectDataNotificationRegistrationEntity, NotificationEventTypeEntity> notificationEventTypeEntity = businessObjectDataNotificationEntity .join(BusinessObjectDataNotificationRegistrationEntity_.notificationEventType); Join<BusinessObjectDataNotificationRegistrationEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectDataNotificationEntity .join(BusinessObjectDataNotificationRegistrationEntity_.businessObjectDefinition); Join<BusinessObjectDefinitionEntity, NamespaceEntity> businessObjectDefinitionNamespaceEntity = businessObjectDefinitionEntity .join(BusinessObjectDefinitionEntity_.namespace); Join<BusinessObjectDataNotificationRegistrationEntity, FileTypeEntity> fileTypeEntity = businessObjectDataNotificationEntity .join(BusinessObjectDataNotificationRegistrationEntity_.fileType, JoinType.LEFT); // Create the standard restrictions (i.e. the standard where clauses). Predicate queryRestriction = builder.equal( builder.upper(notificationEventTypeEntity.get(NotificationEventTypeEntity_.code)), notificationEventTypeCode.toUpperCase()); queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(businessObjectDefinitionNamespaceEntity.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.or( builder.isNull(businessObjectDataNotificationEntity .get(BusinessObjectDataNotificationRegistrationEntity_.usage)), builder.equal( builder.upper(businessObjectDataNotificationEntity .get(BusinessObjectDataNotificationRegistrationEntity_.usage)), businessObjectDataKey.getBusinessObjectFormatUsage().toUpperCase()))); queryRestriction = builder.and(queryRestriction, builder.or( builder.isNull(businessObjectDataNotificationEntity .get(BusinessObjectDataNotificationRegistrationEntity_.fileType)), builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)), businessObjectDataKey.getBusinessObjectFormatFileType().toUpperCase()))); queryRestriction = builder.and(queryRestriction, builder.or( builder.isNull(businessObjectDataNotificationEntity .get(BusinessObjectDataNotificationRegistrationEntity_.businessObjectFormatVersion)), builder.equal( businessObjectDataNotificationEntity .get(BusinessObjectDataNotificationRegistrationEntity_.businessObjectFormatVersion), businessObjectDataKey.getBusinessObjectFormatVersion()))); // Order the results by namespace and notification name. List<Order> orderBy = new ArrayList<>(); orderBy.add(builder.asc(namespaceEntity.get(NamespaceEntity_.code))); orderBy.add(builder.asc( businessObjectDataNotificationEntity.get(BusinessObjectDataNotificationRegistrationEntity_.name))); // Add the clauses for the query. criteria.select(businessObjectDataNotificationEntity).where(queryRestriction).orderBy(orderBy); // Execute the query and return the results. return entityManager.createQuery(criteria).getResultList(); }
From source file:org.finra.herd.dao.impl.AbstractHerdDao.java
/** * TODO This method may be bdata specific. Consider creating new abstract class to group all bdata related DAO. Builds a query restriction predicate for the * sub-query business object data entity as per partition values from the specified main query business object data entity. * * @param builder the criteria builder//from w w w. j a v a 2 s .co m * @param businessObjectDataEntity the business object data entity that appears in the from clause * @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. * * @return the query restriction predicate */ protected Predicate getQueryRestrictionOnPartitionValues(CriteriaBuilder builder, From<?, BusinessObjectDataEntity> businessObjectDataEntity, List<List<String>> partitionFilters) { // Create a query restriction as per specified primary and/or sub-partition values. Predicate predicate = null; for (List<String> partitionFilter : partitionFilters) { // Add restriction for each partition level if the relative partition value is specified in the partition filter. Predicate partitionRestriction = null; for (int partitionLevel = 0; partitionLevel < BusinessObjectDataEntity.MAX_SUBPARTITIONS + 1; partitionLevel++) { String partitionValue = partitionFilter.get(partitionLevel); if (StringUtils.isNotBlank(partitionValue)) { Predicate partitionValueRestriction = builder.equal( businessObjectDataEntity.get(BUSINESS_OBJECT_DATA_PARTITIONS.get(partitionLevel)), partitionValue); partitionRestriction = (partitionRestriction == null ? partitionValueRestriction : builder.and(partitionRestriction, partitionValueRestriction)); } } predicate = (predicate == null ? partitionRestriction : builder.or(predicate, partitionRestriction)); } return predicate; }