List of usage examples for javax.persistence.criteria CriteriaQuery where
CriteriaQuery<T> where(Predicate... restrictions);
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private static List<Long> filterResourceIdsByLastUpdated(EntityManager theEntityManager, final DateRangeParam theLastUpdated, Collection<Long> thePids) { CriteriaBuilder builder = theEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceTable> from = cq.from(ResourceTable.class); cq.select(from.get("myId").as(Long.class)); List<Predicate> lastUpdatedPredicates = createLastUpdatedPredicates(theLastUpdated, builder, from); lastUpdatedPredicates.add(from.get("myId").as(Long.class).in(thePids)); cq.where(SearchBuilder.toArray(lastUpdatedPredicates)); TypedQuery<Long> query = theEntityManager.createQuery(cq); List<Long> resultList = query.getResultList(); return resultList; }
From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java
/** * Finds all {@link AlertHistoryEntity} that match the provided * {@link AlertHistoryRequest}. This method will make JPA do the heavy lifting * of providing a slice of the result set. * * @param request//from w w w . j a va 2 s. c o m * @return */ @RequiresSession public List<AlertHistoryEntity> findAll(AlertHistoryRequest request) { EntityManager entityManager = m_entityManagerProvider.get(); // convert the Ambari predicate into a JPA predicate HistoryPredicateVisitor visitor = new HistoryPredicateVisitor(); PredicateHelper.visit(request.Predicate, visitor); CriteriaQuery<AlertHistoryEntity> query = visitor.getCriteriaQuery(); javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate(); if (null != jpaPredicate) { query.where(jpaPredicate); } // sorting JpaSortBuilder<AlertHistoryEntity> sortBuilder = new JpaSortBuilder<AlertHistoryEntity>(); List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor); query.orderBy(sortOrders); // pagination TypedQuery<AlertHistoryEntity> typedQuery = entityManager.createQuery(query); if (null != request.Pagination) { typedQuery.setFirstResult(request.Pagination.getOffset()); typedQuery.setMaxResults(request.Pagination.getPageSize()); } return m_daoUtils.selectList(typedQuery); }
From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java
@Override public void afterPropertiesSet() throws Exception { this.nameParameter = this.createParameterExpression(String.class, "name"); this.findAllAccountsQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<LocalAccountPersonImpl>>() { @Override//from w w w . j a v a 2 s . co m public CriteriaQuery<LocalAccountPersonImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb .createQuery(LocalAccountPersonImpl.class); final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery .from(LocalAccountPersonImpl.class); accountRoot.fetch(LocalAccountPersonImpl_.attributes, JoinType.LEFT) .fetch(LocalAccountPersonAttributeImpl_.values, JoinType.LEFT); criteriaQuery.select(accountRoot); return criteriaQuery; } }); this.findAccountByNameQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<LocalAccountPersonImpl>>() { @Override public CriteriaQuery<LocalAccountPersonImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb .createQuery(LocalAccountPersonImpl.class); final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery .from(LocalAccountPersonImpl.class); accountRoot.fetch(LocalAccountPersonImpl_.attributes, JoinType.LEFT) .fetch(LocalAccountPersonAttributeImpl_.values, JoinType.LEFT); criteriaQuery.select(accountRoot); criteriaQuery.where(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), nameParameter)); return criteriaQuery; } }); this.findAvailableAttributesQuery = this .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<String>>() { @Override public CriteriaQuery<String> apply(CriteriaBuilder cb) { final CriteriaQuery<String> criteriaQuery = cb.createQuery(String.class); final Root<LocalAccountPersonAttributeImpl> accountRoot = criteriaQuery .from(LocalAccountPersonAttributeImpl.class); criteriaQuery.select(accountRoot.get(LocalAccountPersonAttributeImpl_.name)); criteriaQuery.distinct(true); return criteriaQuery; } }); }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected List<Product> readFilteredActiveProductsByCategoryInternal(Long categoryId, 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 Category since we are browsing Root<CategoryProductXrefImpl> productXref = criteria.from(CategoryProductXrefImpl.class); // We want to filter on attributes from product and sku Join<CategoryProductXref, Product> product = productXref.join("product"); Join<Product, Sku> sku = product.join("defaultSku"); Join<CategoryProductXref, Category> category = productXref.join("category"); // Product objects are what we want back criteria.select(product);/*from w w w . j a v a 2 s .c o m*/ // We only want results from the determine category List<Predicate> restrictions = new ArrayList<Predicate>(); restrictions.add(category.get("id").in(sandBoxHelper.mergeCloneIds(CategoryImpl.class, categoryId))); 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 //typedQuery.setHint(SandBoxHelper.QueryHints.FILTER_INCLUDE, ".*CategoryProductXrefImpl"); return typedQuery.getResultList(); }
From source file:ch.puzzle.itc.mobiliar.business.deploy.boundary.DeploymentBoundary.java
public List<DeploymentEntity> getDeploymentsForRelease(Integer releaseId) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<DeploymentEntity> q = cb.createQuery(DeploymentEntity.class); Root<DeploymentEntity> r = q.from(DeploymentEntity.class); Predicate releasePred = cb.equal(r.<Integer>get("release"), releaseId); q.where(releasePred); TypedQuery<DeploymentEntity> query = em.createQuery(q); return query.getResultList(); }
From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java
/** * Finds all {@link AlertCurrentEntity} that match the provided * {@link AlertCurrentRequest}. This method will make JPA do the heavy lifting * of providing a slice of the result set. * * @param request/* ww w .ja va2s . c o m*/ * @return */ @Transactional public List<AlertCurrentEntity> findAll(AlertCurrentRequest request) { EntityManager entityManager = m_entityManagerProvider.get(); // convert the Ambari predicate into a JPA predicate CurrentPredicateVisitor visitor = new CurrentPredicateVisitor(); PredicateHelper.visit(request.Predicate, visitor); CriteriaQuery<AlertCurrentEntity> query = visitor.getCriteriaQuery(); javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate(); if (null != jpaPredicate) { query.where(jpaPredicate); } // sorting JpaSortBuilder<AlertCurrentEntity> sortBuilder = new JpaSortBuilder<AlertCurrentEntity>(); List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor); query.orderBy(sortOrders); // pagination TypedQuery<AlertCurrentEntity> typedQuery = entityManager.createQuery(query); if (null != request.Pagination) { // prevent JPA errors when -1 is passed in by accident int offset = request.Pagination.getOffset(); if (offset < 0) { offset = 0; } typedQuery.setFirstResult(offset); typedQuery.setMaxResults(request.Pagination.getPageSize()); } List<AlertCurrentEntity> alerts = m_daoUtils.selectList(typedQuery); // if caching is enabled, replace results with cached values when present if (m_configuration.isAlertCacheEnabled()) { alerts = supplementWithCachedAlerts(alerts); } return alerts; }
From source file:org.easy.criteria.CriteriaProcessor.java
/** * Finds all the tuples for the given criteria. Make sure you have provided * columns information in CriteriaContainer that you want in this tuple * result-set.//from w ww . ja v a2 s . com * * @param criteria * - Criteria that you want to apply to this search. * @param distinct * - * @param startIndex * - Pass 0 or less to disable paging. * @param maxResult * - Pass 0 or less to disable paging. * @param lockMode * - Pass NULL if your are not managing transaction. * LockModeType.NONE will through exception if no transaction is * active. * @return - A list of tuples or an empty list if no result were found. */ public <T> List<Tuple> findAllTuple(CriteriaComposer<T> criteria, boolean distinct, QueryProperties properties) { log.trace("CriteriaProcessor.findAllTuple"); Preconditions.checkNotNull(criteria); Class<T> forClass = criteria.getEntityClass(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createQuery(Tuple.class); log.debug("root =" + forClass.getName()); Root<T> root = criteriaQuery.from(forClass); List<Predicate> wherePredicates = new ArrayList<Predicate>(); List<Selection<?>> selectPredicates = new ArrayList<Selection<?>>(); Map<Integer, Order> orderByPredicates = new HashMap<Integer, Order>(0); Map<Integer, Expression<?>> groupByPredicates = new HashMap<Integer, Expression<?>>(0); List<Predicate> havingPredicates = new ArrayList<Predicate>(0); if (criteria != null) { criteria.generateJoins(root); criteria.generateSelect(criteriaBuilder, selectPredicates); criteria.generateGroupBy(criteriaBuilder, groupByPredicates); criteria.generateWhere(criteriaBuilder, wherePredicates); criteria.generateOrderBy(criteriaBuilder, orderByPredicates); criteria.generateHaving(criteriaBuilder, havingPredicates); } Preconditions.checkState(selectPredicates != null); Preconditions.checkArgument(selectPredicates.size() > 0, "No column name found for select clause. " + "Atleast one should be provided for Tuple result. Consider using findAllEntity instead."); criteriaQuery.multiselect(selectPredicates); criteriaQuery.where(wherePredicates.toArray(new Predicate[wherePredicates.size()])); if (orderByPredicates != null && orderByPredicates.size() > 0) { Order[] orderByList = new Order[orderByPredicates.size()]; orderByPredicates.values().toArray(orderByList); criteriaQuery.orderBy(orderByList); } if (groupByPredicates != null && groupByPredicates.size() > 0) { Expression<?>[] groupByList = new Expression<?>[groupByPredicates.size()]; groupByPredicates.values().toArray(groupByList); criteriaQuery.groupBy(groupByList); } criteriaQuery.having(havingPredicates.toArray(new Predicate[havingPredicates.size()])); TypedQuery<Tuple> query = entityManager.createQuery(criteriaQuery); if (properties != null) properties.applyProperties(query); List<Tuple> tuples = query.getResultList(); if (tuples == null) tuples = new ArrayList<Tuple>(0); log.debug("CriteriaProcessor.findAllEntity result size=" + tuples.size()); return tuples; }
From source file:org.openlmis.fulfillment.repository.custom.impl.OrderRepositoryImpl.java
private <T> CriteriaQuery<T> prepareQuery(CriteriaQuery<T> query, OrderSearchParams params, Set<UUID> processingPeriodIds, Pageable pageable, boolean count, Set<UUID> availableSupplyingFacilities, Set<UUID> availableRequestingFacilities) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); Root<Order> root = query.from(Order.class); if (count) {/*from w w w.j a va 2s.c o m*/ CriteriaQuery<Long> countQuery = (CriteriaQuery<Long>) query; query = (CriteriaQuery<T>) countQuery.select(builder.count(root)); } Predicate predicate = builder.conjunction(); predicate = isEqual(SUPPLYING_FACILITY_ID, params.getSupplyingFacilityId(), root, predicate, builder); predicate = isEqual(REQUESTING_FACILITY_ID, params.getRequestingFacilityId(), root, predicate, builder); if (!(isEmpty(availableSupplyingFacilities) && isEmpty(availableRequestingFacilities))) { Predicate orPredicate = builder.disjunction(); orPredicate = isOneOfOr(SUPPLYING_FACILITY_ID, availableSupplyingFacilities, root, orPredicate, builder); orPredicate = isOneOfOr(REQUESTING_FACILITY_ID, availableRequestingFacilities, root, orPredicate, builder); predicate = builder.and(predicate, orPredicate); } predicate = isEqual(PROGRAM_ID, params.getProgramId(), root, predicate, builder); predicate = isOneOf(PROCESSING_PERIOD_ID, processingPeriodIds, root, predicate, builder); predicate = isOneOf(ORDER_STATUS, params.getStatusAsEnum(), root, predicate, builder); query.where(predicate); if (!count && pageable != null && pageable.getSort() != null) { query = addSortProperties(query, root, pageable); } return query; }
From source file:com.yunguchang.data.ApplicationRepository.java
public List<TBusApplyinfoEntity> getApplicationByScheduleId(String scheduleId, PrincipalExt principalExt) { applySecurityFilter("applications", principalExt); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class); Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class); Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT); Join<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleJoin = (Join<TBusApplyinfoEntity, TBusScheduleRelaEntity>) scheduleFetch; Predicate predicate = cb.conjunction(); predicate = cb.and(predicate, cb.equal(scheduleJoin.get(TBusScheduleRelaEntity_.uuid), scheduleId)); cq.where(predicate); return em.createQuery(cq).getResultList(); }
From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java
/** * count entity by ParamInfo//from w ww .j a va 2 s . c o m * * @param paramInfo * @return */ public int count(ParamInfo paramInfo) { EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(entityClass); Root<T> userRoot = cq.from(entityClass); cq.select(cb.count(userRoot)); //build query for paramInfo if (paramInfo != null) { Set<Predicate> andCriteria = new HashSet(); Set<Predicate> orCriteria = new HashSet(); for (ParamItem item : paramInfo.getParamItems()) { Predicate predicate; if (item.getValue() instanceof String) { //fuzy search for string String regExp = "%" + item.getValue() + "%"; predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp); } else { predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue()); } switch (item.getOperator()) { case AND: andCriteria.add(predicate); break; case OR: orCriteria.add(predicate); break; } } if (orCriteria.size() > 0) { Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()])); andCriteria.add(or); } if (andCriteria.size() > 0) { Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()])); cq.where(and); } } TypedQuery<Long> query = em.createQuery(cq); Long result = query.getSingleResult(); return result == null ? 0 : result.intValue(); }