List of usage examples for javax.persistence.criteria CriteriaBuilder like
Predicate like(Expression<String> x, String pattern);
From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletDefinitionDao.java
@Override public void afterPropertiesSet() throws Exception { this.nameParameter = this.createParameterExpression(String.class, "name"); this.titleParameter = this.createParameterExpression(String.class, "title"); this.findAllPortletDefinitions = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletDefinitionImpl>>() { @Override/*from w w w. ja v a2 s . c o m*/ public CriteriaQuery<PortletDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PortletDefinitionImpl> criteriaQuery = cb .createQuery(PortletDefinitionImpl.class); final Root<PortletDefinitionImpl> definitionRoot = criteriaQuery .from(PortletDefinitionImpl.class); criteriaQuery.select(definitionRoot); addFetches(definitionRoot); return criteriaQuery; } }); this.findDefinitionByNameQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletDefinitionImpl>>() { @Override public CriteriaQuery<PortletDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PortletDefinitionImpl> criteriaQuery = cb .createQuery(PortletDefinitionImpl.class); final Root<PortletDefinitionImpl> definitionRoot = criteriaQuery .from(PortletDefinitionImpl.class); criteriaQuery.select(definitionRoot); addFetches(definitionRoot); criteriaQuery .where(cb.equal(definitionRoot.get(PortletDefinitionImpl_.name), nameParameter)); return criteriaQuery; } }); this.findDefinitionByNameOrTitleQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletDefinitionImpl>>() { @Override public CriteriaQuery<PortletDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PortletDefinitionImpl> criteriaQuery = cb .createQuery(PortletDefinitionImpl.class); final Root<PortletDefinitionImpl> definitionRoot = criteriaQuery .from(PortletDefinitionImpl.class); criteriaQuery.select(definitionRoot); addFetches(definitionRoot); criteriaQuery.where(cb.or( cb.equal(definitionRoot.get(PortletDefinitionImpl_.name), nameParameter), cb.equal(definitionRoot.get(PortletDefinitionImpl_.title), titleParameter))); return criteriaQuery; } }); this.searchDefinitionByNameOrTitleQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletDefinitionImpl>>() { @Override public CriteriaQuery<PortletDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PortletDefinitionImpl> criteriaQuery = cb .createQuery(PortletDefinitionImpl.class); final Root<PortletDefinitionImpl> definitionRoot = criteriaQuery .from(PortletDefinitionImpl.class); criteriaQuery.select(definitionRoot); addFetches(definitionRoot); criteriaQuery.where( cb.or(cb.like(definitionRoot.get(PortletDefinitionImpl_.name), nameParameter), cb.like(definitionRoot.get(PortletDefinitionImpl_.title), titleParameter))); return criteriaQuery; } }); }
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 w w.j av a2s .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.common.i18n.dao.TranslationDaoImpl.java
@Override public Translation readTranslation(TranslatedEntity entityType, String entityId, String fieldName, String localeCode, String localeCountryCode, ResultType stage) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Translation> criteria = builder.createQuery(Translation.class); Root<TranslationImpl> root = criteria.from(TranslationImpl.class); criteria.select(root);/* w w w . j a va 2 s.co m*/ List<Predicate> restrictions = new ArrayList<Predicate>(); restrictions.add(builder.equal(root.get("entityType"), entityType.getFriendlyType())); restrictions.add(builder.equal(root.get("entityId"), entityId)); restrictions.add(builder.equal(root.get("fieldName"), fieldName)); restrictions.add(builder.like(root.get("localeCode").as(String.class), localeCode + "%")); try { if (extensionManager != null) { extensionManager.getProxy().setup(TranslationImpl.class, stage); extensionManager.getProxy().refineRetrieve(TranslationImpl.class, stage, builder, criteria, root, restrictions); } criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Translation> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); List<Translation> translations = query.getResultList(); if (!translations.isEmpty()) { return findBestTranslation(localeCountryCode, translations); } else { return null; } } finally { if (extensionManager != null) { extensionManager.getProxy().breakdown(TranslationImpl.class, stage); } } }
From source file:org.broadleafcommerce.core.catalog.dao.IndexFieldCustomPersistenceHandler.java
@Override public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { FilterAndSortCriteria fieldFsc = cto.getCriteriaMap().get("field"); if (fieldFsc != null) { List<String> filterValues = fieldFsc.getFilterValues(); boolean didFilter = false; cto.getCriteriaMap().remove("field"); CriteriaBuilder builder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder(); CriteriaQuery<IndexField> criteria = builder.createQuery(IndexField.class); Root<IndexFieldImpl> root = criteria.from(IndexFieldImpl.class); criteria.select(root);/* w w w. j a v a 2 s . c o m*/ // Check if we are searching for specific field names List<Predicate> restrictions = new ArrayList<Predicate>(); if (CollectionUtils.isNotEmpty(filterValues)) { restrictions.add(builder.like(root.get("field").<String>get("friendlyName"), "%" + filterValues.get(0) + "%")); didFilter = true; } // Check if this filter value has a sort direction associated with it Order order = null; for (FilterAndSortCriteria sortCriteria : cto.getCriteriaMap().values()) { if (sortCriteria.getSortDirection() != null) { Path path = root; try { // Try to find the path to the property in IndexFieldImpl String[] pathParts = sortCriteria.getPropertyId().split("\\."); for (String part : pathParts) { path = path.get(part); } // If we made it here, we have the path, set the sorting (asc/desc) if (sortCriteria.getSortAscending()) { order = builder.asc(path); } else { order = builder.desc(path); } criteria.orderBy(order); break; } catch (IllegalArgumentException e) { // This isn't an actual entity property continue; } } } criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<IndexField> query = dynamicEntityDao.getStandardEntityManager().createQuery(criteria); List<IndexField> indexFields = query.getResultList(); // Convert the result list into a list of entities PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Map<String, FieldMetadata> indexFieldMetadata = helper .getSimpleMergedProperties(IndexField.class.getName(), persistencePerspective); Entity[] entities = helper.getRecords(indexFieldMetadata, indexFields); // We need to get the total number of records available because the entityList returned may not be the full set. Map<String, FieldMetadata> originalProps = helper.getSimpleMergedProperties(IndexField.class.getName(), persistencePerspective); List<FilterMapping> filterMappings = helper.getFilterMappings(persistencePerspective, cto, IndexField.class.getName(), originalProps); int totalRecords = helper.getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings); // Create a Dynamic Result Set from the entity list created above. DynamicResultSet resultSet = new DynamicResultSet(entities, (didFilter ? entities.length : totalRecords)); return resultSet; } DynamicResultSet resultSet = helper.getCompatibleModule(OperationType.BASIC).fetch(persistencePackage, cto); return resultSet; }
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 av a2s .co m*/ // 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.eclipse.jubula.client.core.persistence.NodePM.java
/** * Finds a Test Suite within the currently opened project. * /*ww w . j av a 2 s . c o m*/ * @param testSuiteGuid The GUID of the Test Suite. * @return the Test Suite with the given GUID, or <code>null</code> if * no such Test Suite can be found. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static synchronized ITestSuitePO getTestSuite(String testSuiteGuid) { GeneralStorage gs = GeneralStorage.getInstance(); IProjectPO currentProject = gs.getProject(); if (currentProject != null) { EntityManager s = gs.getMasterSession(); CriteriaBuilder builder = s.getCriteriaBuilder(); CriteriaQuery query = builder.createQuery(); Root from = query.from(NodeMaker.getTestSuitePOClass()); query.select(from).where(builder.like(from.get("guid"), testSuiteGuid), //$NON-NLS-1$ builder.equal(from.get("hbmParentProjectId"), currentProject.getId())); //$NON-NLS-1$ try { Object result = s.createQuery(query).getSingleResult(); if (result instanceof ITestSuitePO) { return (ITestSuitePO) result; } } catch (NoResultException nre) { // No result found. Fall through to return null as per javadoc. } } return null; }
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 . ja va2s .com*/ // 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.DmDaoImpl.java
/** * {@inheritDoc}/* ww w .j a v a 2 s .com*/ */ @Override public Long getStorageFileCount(String storageName, String filePathPrefix) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // The criteria root is the storage files. Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class); // Join to the other tables we can filter on. Join<StorageFileEntity, StorageUnitEntity> storageUnitEntity = storageFileEntity .join(StorageFileEntity_.storageUnit); Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage); // Create path. Expression<Long> storageFileCount = builder.count(storageFileEntity.get(StorageFileEntity_.id)); // Create the standard restrictions (i.e. the standard where clauses). Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)), storageName.toUpperCase()); Predicate filePathRestriction = builder.like(storageFileEntity.get(StorageFileEntity_.path), String.format("%s%%", filePathPrefix)); // Add the clauses for the query. criteria.select(storageFileCount).where(builder.and(storageNameRestriction, filePathRestriction)); return entityManager.createQuery(criteria).getSingleResult(); }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}/*from w w w.ja v a2 s. c o m*/ */ @Override public List<StorageFileEntity> getStorageFileEntities(String storageName, String filePathPrefix) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<StorageFileEntity> criteria = builder.createQuery(StorageFileEntity.class); // The criteria root is the storage files. Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class); // Join to the other tables we can filter on. Join<StorageFileEntity, StorageUnitEntity> storageUnitEntity = storageFileEntity .join(StorageFileEntity_.storageUnit); Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage); // Create the standard restrictions (i.e. the standard where clauses). Predicate filePathRestriction = builder.like(storageFileEntity.get(StorageFileEntity_.path), String.format("%s%%", filePathPrefix)); Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)), storageName.toUpperCase()); // Order the results by file path. Order orderByFilePath = builder.asc(storageFileEntity.get(StorageFileEntity_.path)); criteria.select(storageFileEntity).where(builder.and(filePathRestriction, storageNameRestriction)) .orderBy(orderByFilePath); return entityManager.createQuery(criteria).getResultList(); }
From source file:org.finra.herd.dao.impl.HerdDaoImpl.java
/** * {@inheritDoc}//from ww w. j a v a2 s . co m */ @Override public List<StorageFileEntity> getStorageFilesByStorageAndFilePathPrefix(String storageName, String filePathPrefix) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<StorageFileEntity> criteria = builder.createQuery(StorageFileEntity.class); // The criteria root is the storage files. Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class); // Join to the other tables we can filter on. Join<StorageFileEntity, StorageUnitEntity> storageUnitEntity = storageFileEntity .join(StorageFileEntity_.storageUnit); Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage); // Create the standard restrictions (i.e. the standard where clauses). Predicate filePathRestriction = builder.like(storageFileEntity.get(StorageFileEntity_.path), String.format("%s%%", filePathPrefix)); Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)), storageName.toUpperCase()); // Order the results by file path. Order orderByFilePath = builder.asc(storageFileEntity.get(StorageFileEntity_.path)); criteria.select(storageFileEntity).where(builder.and(filePathRestriction, storageNameRestriction)) .orderBy(orderByFilePath); return entityManager.createQuery(criteria).getResultList(); }