List of usage examples for javax.persistence.criteria CriteriaQuery select
CriteriaQuery<T> select(Selection<? extends T> selection);
From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java
/** * {@inheritDoc}// w w w .j a v a 2s.co m */ @Override public <T extends BaseEntity, C> List<C> findByCriteriaAndMapConstructor(ConstructorCriteria<T, C> criteria) { EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory()); try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<C> cq = cb.createQuery(criteria.getConstructorClass()); Root<T> root = cq.from(criteria.getEntity()); return em.createQuery(cq .select(cb.construct(criteria.getConstructorClass(), criteria.getSelections().stream().map(root::get).toArray(Selection[]::new))) .where(Predicates.from(criteria.getCriteriaAttributes(), cb, root))).getResultList(); } catch (Exception ex) { // NOSONAR throw new JpaException(ex); } finally { JpaUtil.closeEntityManager(em); } }
From source file:net.navasoft.madcoin.backend.model.controller.impl.WorkRequestDataAccess.java
/** * Gets the rows by criteria.//w ww.j a v a 2 s .co m * * @return the rows by criteria * @since 9/09/2014, 11:22:17 AM */ public List<WorkRequests> getRowsByCriteria() { CriteriaQuery<WorkRequests> cq = entityManager.getCriteriaBuilder().createQuery(WorkRequests.class); Root<WorkRequests> rt = cq.from(WorkRequests.class); cq.select(rt); ParameterExpression<String> status = entityManager.getCriteriaBuilder().parameter(String.class); cq.where(entityManager.getCriteriaBuilder().equal(rt.get("processStatus"), status)); TypedQuery<WorkRequests> q = entityManager.createQuery(cq); return q.getResultList(); }
From source file:org.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java
public TypedQuery<Connection> buildLastConnections() { EntityManager em = EntityManagerHolder.get(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Connection> criteria = cb.createQuery(Connection.class); Root<Connection> connection = criteria.from(Connection.class); Predicate predicate = null;//from www . j ava2 s .c o m //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)); } CriteriaQuery<Connection> select = criteria.select(connection).distinct(true); select.where(predicate); select.orderBy(cb.desc(connection.<Long>get(Connection_.id))); TypedQuery<Connection> typedQuery = em.createQuery(select); if (this.limit > 0) { typedQuery.setFirstResult((int) offset); typedQuery.setMaxResults((int) limit); } return typedQuery; }
From source file:net.groupbuy.dao.impl.ProductDaoImpl.java
public List<Product> findList(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, Integer count, List<Filter> filters, List<Order> orders) { 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 + "%"))); }/*from ww w.j a va 2 s . c o 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())))); } } criteriaQuery.where(restrictions); 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.findList(criteriaQuery, null, count, filters, orders); }
From source file:net.groupbuy.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) { 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 + "%"))); }//from w w w .j av 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())))); } } 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:com.vladmihalcea.HibernateCriteriaTest.java
private List<ImageProductDTO> getImageProductDTOs() { return transactionTemplate.execute(new TransactionCallback<List<ImageProductDTO>>() { @Override/* w w w. j a va2 s .co m*/ public List<ImageProductDTO> doInTransaction(TransactionStatus transactionStatus) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<ImageProductDTO> query = cb.createQuery(ImageProductDTO.class); Root<Image> imageRoot = query.from(Image.class); Join<Image, Product> productJoin = imageRoot.join(Image_.product); query.distinct(true); List<Predicate> criteria = new ArrayList<Predicate>(); criteria.add(cb.like(cb.lower(productJoin.get(Product_.name)), "%tv%")); criteria.add(cb.gt(imageRoot.get(Image_.index), 0)); query.where(cb.and(criteria.toArray(new Predicate[criteria.size()]))); query.select(cb.construct(ImageProductDTO.class, imageRoot.get(Image_.name), productJoin.get(Product_.name))).orderBy(cb.asc(imageRoot.get(Image_.name))); return entityManager.createQuery(query).getResultList(); } }); }
From source file:com.netflix.genie.core.jpa.services.JpaJobSearchServiceImpl.java
/** * {@inheritDoc}/*from w ww .j ava 2 s. co m*/ */ @Override public Page<JobSearchResult> findJobs(final String id, final String jobName, final String user, final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final String clusterId, final String commandName, final String commandId, final Date minStarted, final Date maxStarted, final Date minFinished, final Date maxFinished, @NotNull final Pageable page) { log.debug("called"); final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class); final Root<JobEntity> root = countQuery.from(JobEntity.class); final Predicate whereClause = JpaJobSpecs.getFindPredicate(root, cb, id, jobName, user, statuses, tags, clusterName, clusterId == null ? null : this.clusterRepository.findOne(clusterId), commandName, commandId == null ? null : this.commandRepository.findOne(commandId), minStarted, maxStarted, minFinished, maxFinished); countQuery.select(cb.count(root)).where(whereClause); final Long count = this.entityManager.createQuery(countQuery).getSingleResult(); // Use the count to make sure we even need to make this query if (count > 0) { final CriteriaQuery<JobSearchResult> contentQuery = cb.createQuery(JobSearchResult.class); contentQuery.from(JobEntity.class); contentQuery.multiselect(root.get(JobEntity_.id), root.get(JobEntity_.name), root.get(JobEntity_.user), root.get(JobEntity_.status), root.get(JobEntity_.started), root.get(JobEntity_.finished), root.get(JobEntity_.clusterName), root.get(JobEntity_.commandName)); contentQuery.where(whereClause); final Sort sort = page.getSort(); final List<Order> orders = new ArrayList<>(); sort.iterator().forEachRemaining(order -> { if (order.isAscending()) { orders.add(cb.asc(root.get(order.getProperty()))); } else { orders.add(cb.desc(root.get(order.getProperty()))); } }); contentQuery.orderBy(orders); final List<JobSearchResult> results = this.entityManager.createQuery(contentQuery) .setFirstResult(page.getOffset()).setMaxResults(page.getPageSize()).getResultList(); return new PageImpl<>(results, page, count); } else { return new PageImpl<>(Lists.newArrayList(), page, count); } }
From source file:net.groupbuy.dao.impl.BaseDaoImpl.java
protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) { Assert.notNull(criteriaQuery);// w ww. j a v a 2s .co m Assert.notNull(criteriaQuery.getSelection()); Assert.notEmpty(criteriaQuery.getRoots()); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); addRestrictions(criteriaQuery, filters); CriteriaQuery<Long> countCriteriaQuery = criteriaBuilder.createQuery(Long.class); for (Root<?> root : criteriaQuery.getRoots()) { Root<?> dest = countCriteriaQuery.from(root.getJavaType()); dest.alias(getAlias(root)); copyJoins(root, dest); } Root<?> countRoot = getRoot(countCriteriaQuery, criteriaQuery.getResultType()); countCriteriaQuery.select(criteriaBuilder.count(countRoot)); if (criteriaQuery.getGroupList() != null) { countCriteriaQuery.groupBy(criteriaQuery.getGroupList()); } if (criteriaQuery.getGroupRestriction() != null) { countCriteriaQuery.having(criteriaQuery.getGroupRestriction()); } if (criteriaQuery.getRestriction() != null) { countCriteriaQuery.where(criteriaQuery.getRestriction()); } return entityManager.createQuery(countCriteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult(); }
From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java
/** * {@inheritDoc}//from w ww . j ava 2 s . c o m */ @Override public <T extends BaseEntity> List<T> findByINOperator(Class<T> entity, String attributeName, List<Object> values) { EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory()); try { CriteriaQuery<T> cq = em.getCriteriaBuilder().createQuery(entity); Root<T> root = cq.from(entity); Predicate predicate = root.get(attributeName).in(values); return em.createQuery(cq.select(root).where(predicate)).getResultList(); } catch (Exception ex) { // NOSONAR throw new JpaException(ex); } finally { JpaUtil.closeEntityManager(em); } }
From source file:de.ks.idnadrev.information.view.InformationOverviewDS.java
private List<InformationPreviewItem> getResults(String name, List<String> tagNames, Category category, EntityManager em, CriteriaBuilder builder, Class<? extends Information<?>> clazz) { CriteriaQuery<InformationPreviewItem> query = builder.createQuery(InformationPreviewItem.class); Root<? extends Information<?>> root = query.from(clazz); ArrayList<Predicate> filters = new ArrayList<>(); if (!name.isEmpty()) { filters.add(builder.like(builder.lower(root.<String>get(KEY_NAME)), name)); }//from w w w. j a va 2s .c o m if (!tagNames.isEmpty()) { List<Tag> tags = getTags(tagNames, em); SetJoin<TextInfo, Tag> tagJoin = root.joinSet(KEY_TAGS); filters.add(tagJoin.in(tags)); } if (category != null) { filters.add(builder.equal(root.get(KEY_CATEGORY), category)); } query.distinct(true); query.where(filters.toArray(new Predicate[filters.size()])); query.select( builder.construct(InformationPreviewItem.class, root.get(KEY_NAME), root.get(KEY_CREATIONTIME))); List<InformationPreviewItem> resultList = em.createQuery(query).getResultList(); return resultList; }