List of usage examples for javax.persistence.criteria CriteriaQuery select
CriteriaQuery<T> select(Selection<? extends T> selection);
From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java
private List<String> getInterfaceMappingFieldDefinitionIds(final String modelVersion, final List<String> interfaceMappingIds) { final CriteriaBuilder cb = this.em.getCriteriaBuilder(); final CriteriaQuery<String> q = cb.createQuery(String.class); final Root<FieldType> f = q.from(FieldType.class); final Predicate orParentIds = cb.disjunction(); interfaceMappingIds.stream()/* ww w . jav a2s .c om*/ .forEach(id -> orParentIds.getExpressions().add(cb.equal(f.<String>get(FieldType_.parentId), id))); q.select(f.<String>get(FieldType_.fieldTypeDefinitionId)); q.where(cb.equal(f.<String>get(FieldType_.modelVersion), modelVersion), orParentIds); final TypedQuery<String> typedQuery = this.em.createQuery(q); final List<String> value = typedQuery.getResultList(); return value; }
From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java
private List<String> getFlowMappingInterfaceMappingTypeIds(final String modelVersion, final List<String> flowProcessTypeIds) { final List<String> value = new ArrayList<String>(); final CriteriaBuilder cb = this.em.getCriteriaBuilder(); final CriteriaQuery<Long> q = cb.createQuery(Long.class); final Root<FlowMapInOutType> f = q.from(FlowMapInOutType.class); final Predicate orParentIds = cb.disjunction(); flowProcessTypeIds.stream().forEach( id -> orParentIds.getExpressions().add(cb.equal(f.<String>get(FlowMapInOutType_.parentId), id))); q.select(f.<Long>get(FlowMapInOutType_.hjid)); q.where(cb.equal(f.<String>get(FlowMapInOutType_.modelVersion), modelVersion), orParentIds); final TypedQuery<Long> typedQuery = this.em.createQuery(q); typedQuery.getResultList().stream().forEach(hjid -> { value.addAll(this.em.getReference(FlowMapInOutType.class, hjid).getInterfaceMappingId()); });/*from w w w . j a v a2 s .c om*/ return value; }
From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java
@Override public List<ILocalAccountPerson> getPeople(LocalAccountQuery query) { final EntityManager entityManager = this.getEntityManager(); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb.createQuery(LocalAccountPersonImpl.class); final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery.from(LocalAccountPersonImpl.class); final CollectionJoin<LocalAccountPersonImpl, LocalAccountPersonAttributeImpl> attributes = accountRoot .join(LocalAccountPersonImpl_.attributes); final ListJoin<LocalAccountPersonAttributeImpl, String> attributeValues = attributes .join(LocalAccountPersonAttributeImpl_.values); //Due to the joins multiple rows are returned for each result criteriaQuery.distinct(true);//from w w w . j a v a2 s.c o m criteriaQuery.select(accountRoot); final List<Predicate> whereParts = new LinkedList<Predicate>(); final Map<Parameter<String>, String> params = new LinkedHashMap<Parameter<String>, String>(); // if a username has been specified, append it to the query if (query.getName() != null) { whereParts.add(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), this.nameParameter)); params.put(this.nameParameter, query.getName()); } //Build Predicate for each attribute being queried int paramCount = 0; for (Map.Entry<String, List<String>> entry : query.getAttributes().entrySet()) { final List<String> values = entry.getValue(); if (values == null) { continue; } //For each value create a Predicate checking the attribute name and value together for (final String value : values) { if (StringUtils.isBlank(value)) { continue; } //Create Parameter objects for the name and value, stick them in the params map for later use final ParameterExpression<String> nameParam = this.createParameterExpression(String.class, "attrName" + paramCount); final ParameterExpression<String> valueParam = this.createParameterExpression(String.class, "attrValue" + paramCount); params.put(nameParam, entry.getKey()); params.put(valueParam, "%" + value.toLowerCase() + "%"); //Build the and(eq, like) predicate and add it to the list of predicates for the where clause whereParts.add(cb.and(cb.equal(attributes.get(LocalAccountPersonAttributeImpl_.name), nameParam), cb.like(cb.lower(attributeValues.as(String.class)), valueParam))); paramCount++; } } //Add the Predicates to the where clause criteriaQuery.where(cb.or(whereParts.toArray(new Predicate[whereParts.size()]))); //Create the query final TypedQuery<LocalAccountPersonImpl> jpaQuery = this.createCachedQuery(criteriaQuery); //Add all of the stored up parameters to the query for (Map.Entry<Parameter<String>, String> entry : params.entrySet()) { final Parameter<String> parameter = entry.getKey(); final String value = entry.getValue(); jpaQuery.setParameter(parameter, value); } final List<LocalAccountPersonImpl> accounts = jpaQuery.getResultList(); return new ArrayList<ILocalAccountPerson>(accounts); }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected Long readCountAllActiveProductsInternal(Date currentDate) { // Set up the criteria query that specifies we want to return a Long CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // The root of our search is Product Root<ProductImpl> product = criteria.from(ProductImpl.class); // We need to filter on active date on the sku Join<Product, Sku> sku = product.join("defaultSku"); // We want the count of products criteria.select(builder.count(product)); // Ensure the product is currently active List<Predicate> restrictions = new ArrayList<Predicate>(); attachActiveRestriction(currentDate, product, sku, restrictions); // Add the restrictions to the criteria query criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Long> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getSingleResult(); }
From source file:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java
@Override public Long fetchNumberOfMemberRegistersWithoutTerms() { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<MemberRegister> memberRegister = cq.from(MemberRegister.class); Subquery<Long> sq = cq.subquery(Long.class); Root<EvaluationAnswer> evaluationAnswer = sq.from(EvaluationAnswer.class); Join<EvaluationAnswer, QuestionChoicesDef> choiceDef = evaluationAnswer.join(EvaluationAnswer_.answer); Join<QuestionChoicesDef, EvaluationQuestionDef> questionDef = choiceDef .join(QuestionChoicesDef_.evaluationQuestionDef); ParameterExpression<QuestionnaireType> questionnaireType = cb.parameter(QuestionnaireType.class, "questionnaireType"); sq.select(evaluationAnswer.get("memberRegister").get("id")) .where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireType)); cq.select(cb.count(memberRegister.get("id"))).where(cb.not(cb.in(memberRegister.get("id")).value(sq))); TypedQuery<Long> query = entityManager.createQuery(cq); query.setParameter("questionnaireType", QuestionnaireType.TERMS_OF_CONDITION); return query.getSingleResult(); }
From source file:org.apereo.portal.layout.dlm.FragmentDefinitionDao.java
@Override public void afterPropertiesSet() throws Exception { this.nameParameter = this.createParameterExpression(String.class, "name"); this.ownerParameter = this.createParameterExpression(String.class, "ownerId"); this.findAllFragmentsQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<FragmentDefinition>>() { @Override//from w w w .j ava2 s . co m public CriteriaQuery<FragmentDefinition> apply(CriteriaBuilder cb) { final CriteriaQuery<FragmentDefinition> criteriaQuery = cb .createQuery(FragmentDefinition.class); criteriaQuery.from(FragmentDefinition.class); return criteriaQuery; } }); this.findFragmentByNameQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<FragmentDefinition>>() { @Override public CriteriaQuery<FragmentDefinition> apply(CriteriaBuilder cb) { final CriteriaQuery<FragmentDefinition> criteriaQuery = cb .createQuery(FragmentDefinition.class); final Root<FragmentDefinition> fragDefRoot = criteriaQuery.from(FragmentDefinition.class); criteriaQuery.select(fragDefRoot); criteriaQuery.where(cb.equal(fragDefRoot.get(FragmentDefinition_.name), nameParameter)); return criteriaQuery; } }); this.findFragmentByOwnerQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<FragmentDefinition>>() { @Override public CriteriaQuery<FragmentDefinition> apply(CriteriaBuilder cb) { final CriteriaQuery<FragmentDefinition> criteriaQuery = cb .createQuery(FragmentDefinition.class); final Root<FragmentDefinition> fragDefRoot = criteriaQuery.from(FragmentDefinition.class); criteriaQuery.select(fragDefRoot); criteriaQuery.where(cb.equal(fragDefRoot.get(FragmentDefinition_.ownerID), ownerParameter)); return criteriaQuery; } }); }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
@Override public List<Product> readProductsByIds(List<Long> productIds) { if (productIds == null || productIds.size() == 0) { return null; }/*from ww w .j a va2 s . c om*/ if (productIds.size() > 100) { logger.warn("Not recommended to use the readProductsByIds method for long lists of productIds, since " + "Hibernate is required to transform the distinct results. The list of requested" + "product ids was (" + productIds.size() + ") in length."); } // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); Root<ProductImpl> product = criteria.from(ProductImpl.class); FetchParent fetchParent = product.fetch("defaultSku", JoinType.LEFT); if (!dialectHelper.isOracle() && !dialectHelper.isSqlServer()) { fetchParent.fetch("skuMedia", JoinType.LEFT); } criteria.select(product); // We only want results that match the product IDs criteria.where(product.get("id").as(Long.class).in( sandBoxHelper.mergeCloneIds(ProductImpl.class, productIds.toArray(new Long[productIds.size()])))); if (!dialectHelper.isOracle() && !dialectHelper.isSqlServer()) { criteria.distinct(true); } TypedQuery<Product> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); }
From source file:gov.guilin.dao.impl.ProductDaoImpl.java
public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags, Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert, OrderType orderType, Pageable pageable, Set<Supplier> suppliers) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class); Root<Product> root = criteriaQuery.from(Product.class); criteriaQuery.select(root); Predicate restrictions = criteriaBuilder.conjunction(); if (productCategory != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory), criteriaBuilder.like(root.get("productCategory").<String>get("treePath"), "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId() + ProductCategory.TREE_PATH_SEPARATOR + "%"))); }// w w w . ja v a2 s . co m if (brand != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand)); } if (promotion != null) { Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot1 = subquery1.from(Product.class); subquery1.select(subqueryRoot1); subquery1.where(criteriaBuilder.equal(subqueryRoot1, root), criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion)); Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot2 = subquery2.from(Product.class); subquery2.select(subqueryRoot2); subquery2.where(criteriaBuilder.equal(subqueryRoot2, root), criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion)); Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot3 = subquery3.from(Product.class); subquery3.select(subqueryRoot3); subquery3.where(criteriaBuilder.equal(subqueryRoot3, root), criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1), criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3))); } if (tags != null && !tags.isEmpty()) { Subquery<Product> subquery = criteriaQuery.subquery(Product.class); Root<Product> subqueryRoot = subquery.from(Product.class); subquery.select(subqueryRoot); subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags)); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery)); } if (attributeValue != null) { for (Entry<Attribute, String> entry : attributeValue.entrySet()) { String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX + entry.getKey().getPropertyIndex(); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get(propertyName), entry.getValue())); } } if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) { BigDecimal temp = startPrice; startPrice = endPrice; endPrice = temp; } if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("price"), startPrice)); } if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("price"), endPrice)); } if (isMarketable != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isMarketable"), isMarketable)); } if (isList != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList)); } if (isTop != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop)); } if (isGift != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift)); } Path<Integer> stock = root.get("stock"); Path<Integer> allocatedStock = root.get("allocatedStock"); if (isOutOfStock != null) { if (isOutOfStock) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock), criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock)); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock, allocatedStock))); } } if (isStockAlert != null) { Setting setting = SettingUtils.get(); if (isStockAlert) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock), criteriaBuilder.lessThanOrEqualTo(stock, criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock, criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())))); } } //??ADDbyDanielChen 20140502 if ((suppliers != null) && !(suppliers.isEmpty())) { Expression<Supplier> exp = root.get("supplier"); restrictions = criteriaBuilder.and(restrictions, exp.in(suppliers)); } criteriaQuery.where(restrictions); List<Order> orders = pageable.getOrders(); if (orderType == OrderType.priceAsc) { orders.add(Order.asc("price")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.priceDesc) { orders.add(Order.desc("price")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.salesDesc) { orders.add(Order.desc("sales")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.scoreDesc) { orders.add(Order.desc("score")); orders.add(Order.desc("createDate")); } else if (orderType == OrderType.dateDesc) { orders.add(Order.desc("createDate")); } else { orders.add(Order.desc("isTop")); orders.add(Order.desc("modifyDate")); } return super.findPage(criteriaQuery, pageable); }
From source file:org.batoo.jpa.benchmark.BenchmarkTest.java
private void test(final EntityManagerFactory emf, Queue<Runnable> workQueue, int length) { final CriteriaBuilder cb = emf.getCriteriaBuilder(); final CriteriaQuery<Address> cq = cb.createQuery(Address.class); final Root<Person> r = cq.from(Person.class); final Join<Person, Address> a = r.join("addresses"); a.fetch("country", JoinType.LEFT); a.fetch("person", JoinType.LEFT); cq.select(a); final ParameterExpression<Person> p = cb.parameter(Person.class); cq.where(cb.equal(r, p));/*from www .j ava 2 s. co m*/ for (int i = 0; i < length; i++) { workQueue.add(new Runnable() { @Override public void run() { try { BenchmarkTest.this.singleTest(emf, BenchmarkTest.this.createPersons(), cq, p); } catch (final Exception e) { BenchmarkTest.LOG.error(e, "Error while running the test"); } } }); } }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected CriteriaQuery<Product> getCriteriaForActiveProducts(Date currentDate) { // 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 Root<ProductImpl> product = criteria.from(ProductImpl.class); // We need to filter on active date on the sku Join<Product, Sku> sku = product.join("defaultSku"); product.fetch("defaultSku"); // Product objects are what we want back criteria.select(product); // Ensure the product is currently active List<Predicate> restrictions = new ArrayList<Predicate>(); attachActiveRestriction(currentDate, product, sku, restrictions); // Add the restrictions to the criteria query criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); //Add ordering so that paginated queries are consistent criteria.orderBy(builder.asc(product.get("id"))); return criteria; }