List of usage examples for javax.persistence.criteria CriteriaQuery where
CriteriaQuery<T> where(Predicate... restrictions);
From source file:net.groupbuy.dao.impl.CouponCodeDaoImpl.java
public Long count(Coupon coupon, Member member, Boolean hasBegun, Boolean hasExpired, Boolean isUsed) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<CouponCode> criteriaQuery = criteriaBuilder.createQuery(CouponCode.class); Root<CouponCode> root = criteriaQuery.from(CouponCode.class); criteriaQuery.select(root);//from w w w.j a v a2 s .c o m Predicate restrictions = criteriaBuilder.conjunction(); Path<Coupon> couponPath = root.get("coupon"); if (coupon != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(couponPath, coupon)); } if (member != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member)); } if (hasBegun != null) { if (hasBegun) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(couponPath.get("beginDate").isNull(), criteriaBuilder.lessThanOrEqualTo(couponPath.<Date>get("beginDate"), new Date()))); } else { restrictions = criteriaBuilder.and(restrictions, couponPath.get("beginDate").isNotNull(), criteriaBuilder.greaterThan(couponPath.<Date>get("beginDate"), new Date())); } } if (hasExpired != null) { if (hasExpired) { restrictions = criteriaBuilder.and(restrictions, couponPath.get("endDate").isNotNull(), criteriaBuilder.lessThan(couponPath.<Date>get("endDate"), new Date())); } else { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(couponPath.get("endDate").isNull(), criteriaBuilder.greaterThanOrEqualTo(couponPath.<Date>get("endDate"), new Date()))); } } if (isUsed != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isUsed"), isUsed)); } criteriaQuery.where(restrictions); return super.count(criteriaQuery, null); }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
private void loadResourcesByPid(Collection<Long> theIncludePids, List<IResource> theResourceListToPopulate, BundleEntrySearchModeEnum theBundleEntryStatus) { if (theIncludePids.isEmpty()) { return;//from ww w . ja v a2 s .co m } Map<Long, Integer> position = new HashMap<Long, Integer>(); for (Long next : theIncludePids) { position.put(next, theResourceListToPopulate.size()); theResourceListToPopulate.add(null); } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<ResourceTable> cq = builder.createQuery(ResourceTable.class); Root<ResourceTable> from = cq.from(ResourceTable.class); cq.where(from.get("myId").in(theIncludePids)); TypedQuery<ResourceTable> q = myEntityManager.createQuery(cq); for (ResourceTable next : q.getResultList()) { Class<? extends IBaseResource> resourceType = getContext().getResourceDefinition(next.getResourceType()) .getImplementingClass(); IResource resource = (IResource) toResource(resourceType, next); Integer index = position.get(next.getId()); if (index == null) { ourLog.warn("Got back unexpected resource PID {}", next.getId()); continue; } ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.put(resource, theBundleEntryStatus); theResourceListToPopulate.set(index, resource); } }
From source file:org.openmeetings.app.data.user.Usermanagement.java
public Users getUserByIdAndDeleted(Long id) throws Exception { log.debug("Usermanagement.getUserById"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Users> cq = cb.createQuery(Users.class); Root<Users> c = cq.from(Users.class); Predicate condition = cb.equal(c.get("user_id"), id); cq.where(condition); TypedQuery<Users> q = em.createQuery(cq); Users u = null;/* w w w. jav a 2 s . com*/ try { u = q.getSingleResult(); } catch (NoResultException e) { // u=null} } return u; }
From source file:gov.guilin.dao.impl.ProductDaoImpl.java
public List<Object[]> findSalesList(Date beginDate, Date endDate, Integer count) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class); Root<Product> product = criteriaQuery.from(Product.class); Join<Product, OrderItem> orderItems = product.join("orderItems"); Join<Product, gov.guilin.entity.Order> order = orderItems.join("order"); criteriaQuery.multiselect(product.get("id"), product.get("sn"), product.get("name"), product.get("fullName"), product.get("price"), criteriaBuilder.sum(orderItems.<Integer>get("quantity")), criteriaBuilder.sum(criteriaBuilder .prod(orderItems.<Integer>get("quantity"), orderItems.<BigDecimal>get("price")))); Predicate restrictions = criteriaBuilder.conjunction(); if (beginDate != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(order.<Date>get("createDate"), beginDate)); }//from w w w . j a va2 s . co m if (endDate != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(order.<Date>get("createDate"), endDate)); } restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(order.get("orderStatus"), OrderStatus.completed), criteriaBuilder.equal(order.get("paymentStatus"), PaymentStatus.paid)); criteriaQuery.where(restrictions); criteriaQuery.groupBy(product.get("id"), product.get("sn"), product.get("name"), product.get("fullName"), product.get("price")); criteriaQuery.orderBy(criteriaBuilder.desc(criteriaBuilder.sum( criteriaBuilder.prod(orderItems.<Integer>get("quantity"), orderItems.<BigDecimal>get("price"))))); TypedQuery<Object[]> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT); if (count != null && count >= 0) { query.setMaxResults(count); } return query.getResultList(); }
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);//from w w w. j a v a 2s.co 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:eu.domibus.common.dao.ErrorLogDao.java
public List<ErrorLogEntry> findPaged(int from, int max, String column, boolean asc, HashMap<String, Object> filters) { CriteriaBuilder cb = this.em.getCriteriaBuilder(); CriteriaQuery<ErrorLogEntry> cq = cb.createQuery(ErrorLogEntry.class); Root<ErrorLogEntry> ele = cq.from(ErrorLogEntry.class); cq.select(ele);//from ww w . ja va 2s . c o m List<Predicate> predicates = new ArrayList<Predicate>(); for (Map.Entry<String, Object> filter : filters.entrySet()) { if (filter.getValue() != null) { if (filter.getValue() instanceof String) { if (!filter.getValue().toString().isEmpty()) { switch (filter.getKey().toString()) { case "": break; case "timestampFrom": predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("timestamp"), Timestamp.valueOf(filter.getValue().toString()))); break; case "timestampTo": predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("timestamp"), Timestamp.valueOf(filter.getValue().toString()))); break; case "notifiedFrom": predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("notified"), Timestamp.valueOf(filter.getValue().toString()))); break; case "notifiedTo": predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("notified"), Timestamp.valueOf(filter.getValue().toString()))); break; default: predicates.add(cb.like(ele.<String>get(filter.getKey()), (String) filter.getValue())); break; } } } else { predicates.add(cb.equal(ele.<String>get(filter.getKey()), filter.getValue())); } } } cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); if (column != null) { if (asc) { cq.orderBy(cb.asc(ele.get(column))); } else { cq.orderBy(cb.desc(ele.get(column))); } } final TypedQuery<ErrorLogEntry> query = this.em.createQuery(cq); query.setFirstResult(from); query.setMaxResults(max); return query.getResultList(); }
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * query for a list of users// ww w . j av a 2s.c o m * * @param users_id * @param user_level * @param start * @param max * @param orderby * @return */ public SearchResult<Users> getUsersList(long user_level, int start, int max, String orderby, boolean asc) { try { if (authLevelManagement.checkAdminLevel(user_level)) { SearchResult<Users> sresult = new SearchResult<Users>(); sresult.setObjectName(Users.class.getName()); sresult.setRecords(usersDao.selectMaxFromUsers()); // get all users CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Users> cq = cb.createQuery(Users.class); Root<Users> c = cq.from(Users.class); Predicate condition = cb.equal(c.get("deleted"), "false"); cq.where(condition); cq.distinct(asc); if (asc) { cq.orderBy(cb.asc(c.get(orderby))); } else { cq.orderBy(cb.desc(c.get(orderby))); } TypedQuery<Users> q = em.createQuery(cq); q.setFirstResult(start); q.setMaxResults(max); List<Users> ll = q.getResultList(); sresult.setResult(ll); return sresult; } } catch (Exception ex2) { log.error("[getUsersList] " + ex2); } return null; }
From source file:org.apereo.portal.groups.pags.dao.jpa.JpaPersonAttributesGroupDefinitionDao.java
@Override public void afterPropertiesSet() throws Exception { this.nameParameter = this.createParameterExpression(String.class, "name"); this.findAllDefinitionsQuery = this.createCriteriaQuery( new Function<CriteriaBuilder, CriteriaQuery<PersonAttributesGroupDefinitionImpl>>() { @Override// w w w.ja v a 2s .c o m public CriteriaQuery<PersonAttributesGroupDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PersonAttributesGroupDefinitionImpl> criteriaQuery = cb .createQuery(PersonAttributesGroupDefinitionImpl.class); criteriaQuery.from(PersonAttributesGroupDefinitionImpl.class); return criteriaQuery; } }); this.groupDefinitionByNameQuery = this.createCriteriaQuery( new Function<CriteriaBuilder, CriteriaQuery<PersonAttributesGroupDefinitionImpl>>() { @Override public CriteriaQuery<PersonAttributesGroupDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PersonAttributesGroupDefinitionImpl> criteriaQuery = cb .createQuery(PersonAttributesGroupDefinitionImpl.class); Root<PersonAttributesGroupDefinitionImpl> root = criteriaQuery .from(PersonAttributesGroupDefinitionImpl.class); criteriaQuery.select(root).where(cb.equal(root.get("name"), nameParameter)); return criteriaQuery; } }); this.parentGroupDefinitionsQuery = this.createCriteriaQuery( new Function<CriteriaBuilder, CriteriaQuery<PersonAttributesGroupDefinitionImpl>>() { @Override public CriteriaQuery<PersonAttributesGroupDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PersonAttributesGroupDefinitionImpl> criteriaQuery = cb .createQuery(PersonAttributesGroupDefinitionImpl.class); Root<PersonAttributesGroupDefinitionImpl> root = criteriaQuery .from(PersonAttributesGroupDefinitionImpl.class); Join<PersonAttributesGroupDefinitionImpl, PersonAttributesGroupDefinitionImpl> members = root .join(PersonAttributesGroupDefinitionImpl_.members); criteriaQuery.where( cb.equal(members.get(PersonAttributesGroupDefinitionImpl_.name), nameParameter)); return criteriaQuery; } }); }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
private Set<Long> addPredicateId(Set<Long> theExistingPids, Set<Long> thePids) { if (thePids == null || thePids.isEmpty()) { return Collections.emptySet(); }/*from w ww. j a va 2s .c o m*/ CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceTable> from = cq.from(ResourceTable.class); cq.select(from.get("myId").as(Long.class)); Predicate typePredicate = builder.equal(from.get("myResourceType"), myResourceName); Predicate idPrecidate = from.get("myId").in(thePids); cq.where(builder.and(typePredicate, idPrecidate)); TypedQuery<Long> q = myEntityManager.createQuery(cq); HashSet<Long> found = new HashSet<Long>(q.getResultList()); if (!theExistingPids.isEmpty()) { theExistingPids.retainAll(found); } return found; }
From source file:com.yunguchang.data.ApplicationRepository.java
public List<TAzCarinfoEntity> listAllCandidateCars(String[] applicationIds, String keyword, Integer offset, Integer limit, PrincipalExt principalExt) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TAzCarinfoEntity> cq = cb.createQuery(TAzCarinfoEntity.class); Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class); carRoot.fetch(TAzCarinfoEntity_.driver, JoinType.LEFT); cq.select(carRoot);/*w w w. j a va2 s .c o m*/ Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class); applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, null, cb, principalExt); Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.clzt), "02"), cb.or(cb.equal(carRoot.get(TAzCarinfoEntity_.repairingState), RepairingState.NONE.id()), cb.isNull(carRoot.get(TAzCarinfoEntity_.repairingState)) ), cb.not(cb.exists(overlapScheduleCarSubQuery)) ); if (keyword != null) { predicate = cb.and(predicate, cb.or(cb.like(carRoot.get(TAzCarinfoEntity_.sysOrg).get(TSysOrgEntity_.orgname), "%" + keyword + "%"), cb.like(carRoot.get(TAzCarinfoEntity_.cphm), "%" + keyword + "%"))); } cq.where(predicate); cq.orderBy(cb.asc(carRoot.get(TAzCarinfoEntity_.cphm))); TypedQuery<TAzCarinfoEntity> query = em.createQuery(cq); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } applySecurityFilter("cars", principalExt); return query.getResultList(); }