List of usage examples for javax.persistence.criteria CriteriaQuery where
CriteriaQuery<T> where(Predicate... restrictions);
From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java
/** * Get the list of {@link FlowType}s matching the name pattern. * * @param modelVersion/* w w w. j a va2s . c om*/ * the model version. * @param namePattern * the name pattern. * @return the list of {@link FlowType}s matching the name pattern. * @since 3.5.1 */ @Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED) public List<FlowType> getFlowByNamePattern(final String modelVersion, final Collection<String> namePattern) { final CriteriaBuilder cb = this.em.getCriteriaBuilder(); final CriteriaQuery<FlowType> q = cb.createQuery(FlowType.class); final Root<FlowType> f = q.from(FlowType.class); final Predicate or = cb.disjunction(); namePattern.stream() .forEach(id -> or.getExpressions().add(cb.like(f.<String>get(FlowType_.name), "%" + id + "%"))); final Predicate and = cb.conjunction(); and.getExpressions().add(cb.equal(f.<String>get(FlowType_.modelVersion), modelVersion)); and.getExpressions().add(or); q.where(and); final TypedQuery<FlowType> typedQuery = this.em.createQuery(q); final List<FlowType> value = typedQuery.getResultList(); value.stream().forEach(ft -> EagerLoader.load(ft)); return value; }
From source file:net.groupbuy.dao.impl.OrderDaoImpl.java
public BigDecimal getSalesAmount(Date beginDate, Date endDate) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<BigDecimal> criteriaQuery = criteriaBuilder.createQuery(BigDecimal.class); Root<Order> root = criteriaQuery.from(Order.class); criteriaQuery.select(criteriaBuilder.sum(root.<BigDecimal>get("amountPaid"))); Predicate restrictions = criteriaBuilder.conjunction(); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderStatus"), OrderStatus.completed)); if (beginDate != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate)); }/*from w ww. j a v a2s.c om*/ if (endDate != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate)); } criteriaQuery.where(restrictions); return entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult(); }
From source file:net.shopxx.dao.impl.OrderDaoImpl.java
public BigDecimal completeOrderAmount(Date beginDate, Date endDate) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<BigDecimal> criteriaQuery = criteriaBuilder.createQuery(BigDecimal.class); Root<Order> root = criteriaQuery.from(Order.class); criteriaQuery.select(criteriaBuilder.sum(root.<BigDecimal>get("amount"))); Predicate restrictions = criteriaBuilder.conjunction(); if (beginDate != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("completeDate"), beginDate)); }//from ww w . j a v a2 s.c o m if (endDate != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(root.<Date>get("completeDate"), endDate)); } criteriaQuery.where(restrictions); BigDecimal result = entityManager.createQuery(criteriaQuery).getSingleResult(); return result != null ? result : BigDecimal.ZERO; }
From source file:net.groupbuy.dao.impl.OrderDaoImpl.java
public Integer getSalesVolume(Date beginDate, Date endDate) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Integer> criteriaQuery = criteriaBuilder.createQuery(Integer.class); Root<Order> root = criteriaQuery.from(Order.class); criteriaQuery.select(criteriaBuilder.sum(root.join("orderItems").<Integer>get("shippedQuantity"))); Predicate restrictions = criteriaBuilder.conjunction(); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("orderStatus"), OrderStatus.completed)); if (beginDate != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate)); }/* ww w. j a v a 2s .c o m*/ if (endDate != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate)); } criteriaQuery.where(restrictions); return entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult(); }
From source file:com.vladmihalcea.HibernateCriteriaTest.java
private List<Product> getProducts_Mercilessly() { return transactionTemplate.execute(new TransactionCallback<List<Product>>() { @Override/* w w w . j a va 2 s . co m*/ public List<Product> doInTransaction(TransactionStatus transactionStatus) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Product> query = cb.createQuery(Product.class); Root<Product> product = query.from(Product.class); query.select(product); query.distinct(true); List<Predicate> criteria = new ArrayList<Predicate>(); criteria.add(cb.like(cb.lower(product.get(Product_.name)), "%tv%")); Subquery<Long> subQuery = query.subquery(Long.class); Root<Image> infoRoot = subQuery.from(Image.class); Join<Image, Product> productJoin = infoRoot.join(Image_.product); subQuery.select(productJoin.<Long>get(Product_.id)); subQuery.where(cb.gt(infoRoot.get(Image_.index), 0)); criteria.add(cb.in(product.get(Product_.id)).value(subQuery)); query.where(cb.and(criteria.toArray(new Predicate[criteria.size()]))); return entityManager.createQuery(query).getResultList(); } }); }
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; }// ww w.j ava2 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:it.attocchi.jpa2.JPAEntityFilter.java
public CriteriaQuery<T> getCriteria(Class<T> clazz, EntityManagerFactory emf) throws Exception { // CriteriaBuilder CriteriaBuilder criteriaBuilder = emf.getCriteriaBuilder(); CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(clazz); Root<T> root = criteriaQuery.from(clazz); criteriaQuery.select(root);/* w ww.j av a2 s. c o m*/ // criteria.where( builder.equal( personRoot.get( Utente_.eyeColor ), // "brown" ) ); List<Predicate> predicateList = new ArrayList<Predicate>(); // buildWhere(emf, predicateList, criteriaQuery, criteriaBuilder, root); // // Predicate[] predicates = new Predicate[predicateList.size()]; // predicateList.toArray(predicates); Predicate[] predicates = getWherePredicates(emf, predicateList, criteriaQuery, criteriaBuilder, root); Predicate wherePredicate = criteriaBuilder.and(predicates); criteriaQuery.where(wherePredicate); // buildSort(criteriaQuery, criteriaBuilder, root); List<Order> orders = new ArrayList<Order>(); buildSort(orders, criteriaQuery, criteriaBuilder, root); if (ListUtils.isNotEmpty(orders)) criteriaQuery.orderBy(orders); return criteriaQuery; }
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);// w w w . ja va 2 s.c om final ParameterExpression<Person> p = cb.parameter(Person.class); cq.where(cb.equal(r, p)); 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:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
public <T extends ObjectType> PrismObject<T> getObjectInternal(Session session, Class<T> type, String oid, Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate, OperationResult operationResult) throws ObjectNotFoundException, SchemaException, DtoTranslationException { boolean lockedForUpdateViaHibernate = false; boolean lockedForUpdateViaSql = false; LockOptions lockOptions = new LockOptions(); //todo fix lock for update!!!!! if (lockForUpdate) { if (getConfiguration().isLockForUpdateViaHibernate()) { lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE); lockedForUpdateViaHibernate = true; } else if (getConfiguration().isLockForUpdateViaSql()) { LOGGER.trace("Trying to lock object {} for update (via SQL)", oid); long time = System.currentTimeMillis(); NativeQuery q = session.createNativeQuery("select oid from m_object where oid = ? for update"); q.setParameter(1, oid);//from www . j av a 2 s .c om Object result = q.uniqueResult(); if (result == null) { return throwObjectNotFoundException(type, oid); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Locked via SQL (in {} ms)", System.currentTimeMillis() - time); } lockedForUpdateViaSql = true; } } if (LOGGER.isTraceEnabled()) { if (lockedForUpdateViaHibernate) { LOGGER.trace("Getting object {} with locking for update (via hibernate)", oid); } else if (lockedForUpdateViaSql) { LOGGER.trace("Getting object {}, already locked for update (via SQL)", oid); } else { LOGGER.trace("Getting object {} without locking for update", oid); } } GetObjectResult fullObject = null; if (!lockForUpdate) { Query query = session.getNamedQuery("get.object"); query.setParameter("oid", oid); query.setResultTransformer(GetObjectResult.RESULT_STYLE.getResultTransformer()); query.setLockOptions(lockOptions); fullObject = (GetObjectResult) query.uniqueResult(); } else { // we're doing update after this get, therefore we load full object right now // (it would be loaded during merge anyway) // this just loads object to hibernate session, probably will be removed later. Merge after this get // will be faster. Read and use object only from fullObject column. // todo remove this later [lazyman] Class clazz = ClassMapper.getHQLTypeClass(type); CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(clazz); cq.where(cb.equal(cq.from(clazz).get("oid"), oid)); Query query = session.createQuery(cq); query.setLockOptions(lockOptions); RObject obj = (RObject) query.uniqueResult(); if (obj != null) { fullObject = new GetObjectResult(obj.getOid(), obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(), obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount(), obj.getBooleansCount()); } } LOGGER.trace("Got it."); if (fullObject == null) { throwObjectNotFoundException(type, oid); } LOGGER.trace("Transforming data to JAXB type."); PrismObject<T> prismObject = updateLoadedObject(fullObject, type, oid, options, null, session, operationResult); validateObjectType(prismObject, type); // this was implemented to allow report parsing errors as warnings to upper layers; // however, it causes problems when serialization problems are encountered: in such cases, we put // FATAL_ERROR to the result here, and it should be then removed or muted (which is a complication) // -- so, as the parsing errors are not implemented, we disabled this code as well // subResult.computeStatusIfUnknown(); // if (subResult.isWarning() || subResult.isError() || subResult.isInProgress()) { // prismObject.asObjectable().setFetchResult(subResult.createOperationResultType()); // } return prismObject; }
From source file:dtu.ds.warnme.dao.impl.EventsDaoImpl.java
@Override public List<EventEntity> getNearestEvents(Float nLat, Float sLat, Float eLng, Float wLng, EventType... eventTypes) {// w w w .j a va2s . c o m CriteriaBuilder criteriaBuilder = getCriteriaBuilder(); CriteriaQuery<EventEntity> criteriaQuery = criteriaBuilder.createQuery(EventEntity.class); Root<EventEntity> root = criteriaQuery.from(EventEntity.class); List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get(EventEntity_.latitude), nLat)); predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(EventEntity_.latitude), sLat)); predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get(EventEntity_.longitude), eLng)); predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(EventEntity_.longitude), wLng)); if (ArrayUtils.isNotEmpty(eventTypes)) { List<Predicate> eventTypePredicates = new ArrayList<Predicate>(); for (EventType et : eventTypes) { eventTypePredicates.add(criteriaBuilder.equal(root.get(EventEntity_.eventType), et)); } predicates.add(criteriaBuilder.and( criteriaBuilder.or(eventTypePredicates.toArray(new Predicate[eventTypePredicates.size()])))); } criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])); return getAllByCriteria(criteriaQuery); }