List of usage examples for javax.persistence.criteria CriteriaBuilder equal
Predicate equal(Expression<?> x, Object y);
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);/* w w w .ja v a 2 s . c o m*/ 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 + "%"))); } 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:cn.buk.hotel.dao.HotelDaoImpl.java
@Override public List<HotelInfo> searchAvailableHotel(HotelSearchCriteria sc) { List<HotelInfo> hotelInfos = null; try {//w w w.j a v a2s. c om //body CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaQuery<HotelInfo> cq = cb.createQuery(HotelInfo.class); Root<HotelInfo> root = cq.from(HotelInfo.class); root.alias("h"); List<Predicate> predicates = new ArrayList<Predicate>(); Predicate predicate = cb.equal(root.get(HotelInfo_.cityId), sc.getCityId()); predicates.add(predicate); /** * ratePlanStatus-1???) yfddai 2015-1-8 */ predicate = cb.notEqual(root.get(HotelInfo_.ratePlanStatus), -1); predicates.add(predicate); if (sc.getDistrictId() > 0) { predicate = cb.equal(root.get(HotelInfo_.areaId), sc.getDistrictId()); predicates.add(predicate); } if (sc.getHotelName() != null && sc.getHotelName().trim().length() > 0) { predicate = cb.like(root.get(HotelInfo_.hotelName), "%" + sc.getHotelName() + "%"); predicates.add(predicate); } if (sc.getStar() != null && sc.getStar().length() > 0) { Join<HotelInfo, HotelAward> hotelAward = root.join("hotelAwards", JoinType.LEFT); hotelAward.alias("ha"); predicates.add(cb.equal(hotelAward.get("provider"), "HotelStarRate")); String[] stars = sc.getStar().split(","); Predicate p0 = cb.disjunction(); for (String star : stars) { if (star.length() == 0) continue; int starLevel = Integer.parseInt(star); if (starLevel == 2) p0 = cb.or(p0, cb.le(hotelAward.get(HotelAward_.rating), starLevel)); else p0 = cb.or(p0, cb.equal(hotelAward.get("rating"), starLevel)); } predicates.add(p0); } if (sc.getZoneId() > 0) { Join<HotelInfo, HotelAddressZone> hotelZone = root.join(HotelInfo_.hotelAddressZones, JoinType.LEFT); hotelZone.alias("hz"); predicate = cb.equal(hotelZone.get(HotelAddressZone_.zoneCode), sc.getZoneId()); predicates.add(predicate); } // count items CriteriaQuery<Long> cq0 = cb.createQuery(Long.class); Root<HotelInfo> root0 = cq0.from(HotelInfo.class); root0.alias("h"); if (sc.getStar() != null && sc.getStar().length() > 0) { Join<HotelInfo, HotelAward> hotelAward0 = root0.join("hotelAwards", JoinType.LEFT); hotelAward0.alias("ha"); } if (sc.getZoneId() > 0) { Join<HotelInfo, HotelAddressZone> hotelZone0 = root0.join(HotelInfo_.hotelAddressZones, JoinType.LEFT); hotelZone0.alias("hz"); } cq0.select(cb.count(root0)).where(predicates.toArray(new Predicate[0])); Long count = getEm().createQuery(cq0).getSingleResult(); sc.getPage().setRowCount(count.intValue()); int firstPosition = (sc.getPage().getPageNo() - 1) * sc.getPage().getPageSize(); cq.select(root).where(predicates.toArray(new Predicate[0])); hotelInfos = getEm().createQuery(cq).setFirstResult(firstPosition) .setMaxResults(sc.getPage().getPageSize()).getResultList(); } catch (PersistenceException e) { logger.error(e.getMessage()); } return hotelInfos == null ? new ArrayList<HotelInfo>() : hotelInfos; }
From source file:de.whs.poodle.repositories.StatisticsRepository.java
public List<Statistic> getStatistics(FeedbackSearchCriteria s, int instructorId, int limit) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Statistic> cq = cb.createQuery(Statistic.class); Root<Statistic> statistic = cq.from(Statistic.class); /* fetch the exercises immediately so they don't have to * be lazy-fetched one by one while rendering the table rows. */ statistic.fetch("exercise"); // join we need to match the course Join<Statistic, Course> course = statistic.join("courseTerm").join("course"); // create empty "and" predicate Predicate where = cb.conjunction(); // only non-empty Predicate notEmpty = cb.isFalse(statistic.get("empty")); where = cb.and(where, notEmpty);// ww w .j a v a 2s .c o m // only statistics for courses that the instructor has access to Predicate hasInstructorAccessToCourse = cb.isTrue(cb.function("has_instructor_access_to_course", Boolean.class, course.get("id"), cb.literal(instructorId))); where = cb.and(where, hasInstructorAccessToCourse); // filter by courseId if (s.getCourseId() != 0) { Predicate courseMatches = cb.equal(course.get("id"), s.getCourseId()); where = cb.and(where, courseMatches); } // filter by student if (s.getStudent() != null) { Predicate studentMatches = cb.equal(statistic.get("student").get("id"), s.getStudent().getId()); where = cb.and(where, studentMatches); } cq.where(where); // order by date cq.orderBy(cb.desc(statistic.get("completedAt"))); return em.createQuery(cq).setMaxResults(limit).getResultList(); }
From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java
/** * list entity by CriteriaInfo//from w ww .jav a 2 s. co m * * @param criteriaInfo * @return PagedResult */ public PagedResult<T> list(CriteriaInfo criteriaInfo) { EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(entityClass); Root<T> userRoot = cq.from(entityClass); cq.select(userRoot); ParamInfo paramInfo = criteriaInfo.getParamInfo(); PageInfo pageInfo = criteriaInfo.getPageInfo(); SortInfo sortInfo = criteriaInfo.getSortInfo(); //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); } } //build query for sortInfo Set<Order> orderPredicate = new HashSet<>(); if (sortInfo != null) { for (SortItem item : sortInfo.getSortItems()) { if (item.isDescending()) { orderPredicate.add(cb.desc(userRoot.get(item.getFieldName()))); } else { orderPredicate.add(cb.asc(userRoot.get(item.getFieldName()))); } } } if (orderPredicate.size() > 0) { cq.orderBy(orderPredicate.toArray(new Order[orderPredicate.size()])); } TypedQuery<T> query = em.createQuery(cq); //set result range if (pageInfo != null) { query.setFirstResult(pageInfo.getOffset()); query.setMaxResults(pageInfo.getSize()); } int totalSize; if (paramInfo != null && paramInfo.getParamItems().size() > 0) { totalSize = count(paramInfo); } else { totalSize = count(); } return new PagedResult(query.getResultList(), totalSize); }
From source file:com.yunguchang.data.ApplicationRepository.java
public TBusApplyinfoEntity getApplicationById(String id) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class); Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class); cq.where(cb.equal(applyRoot.get(TBusApplyinfoEntity_.uuid), id)); return Iterables.getFirst(em.createQuery(cq).getResultList(), null); }
From source file:com.yunguchang.data.ApplicationRepository.java
public TBusApplyinfoEntity getApplicationByNo(String applyNo, PrincipalExt principalExtOrNull) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class); Root<TBusApplyinfoEntity> scheduleRoot = cq.from(TBusApplyinfoEntity.class); cq.where(cb.equal(scheduleRoot.get(TBusApplyinfoEntity_.applyno), applyNo)); return Iterables.getFirst(em.createQuery(cq).getResultList(), null); }
From source file:ch.puzzle.itc.mobiliar.business.server.boundary.ServerView.java
private Predicate addFilters(Predicate p, CriteriaBuilder cb, String hostFilter, String appServerFilter, String runtimeFilter, String nodeFilter, String contextFilter, Path<String> hostPath, Path<String> appServerPath, Path<String> runtimePath, Path<String> nodePath, Path<String> contextPath) { if (!StringUtils.isEmpty(hostFilter)) { p = cb.and(p,/*from ww w . j a v a 2 s . c om*/ cb.like(cb.lower(hostPath), hostFilter.toLowerCase(), JpaWildcardConverter.ESCAPE_CHARACTER)); } if (!StringUtils.isEmpty(nodeFilter)) { p = cb.and(p, cb.like(cb.lower(nodePath), nodeFilter.toLowerCase(), JpaWildcardConverter.ESCAPE_CHARACTER)); } if (!StringUtils.isEmpty(appServerFilter)) { p = cb.and(p, cb.like(cb.lower(appServerPath), appServerFilter.toLowerCase(), JpaWildcardConverter.ESCAPE_CHARACTER)); } if (!StringUtils.isEmpty(runtimeFilter)) { p = cb.and(p, cb.like(cb.lower(runtimePath), runtimeFilter.toLowerCase(), JpaWildcardConverter.ESCAPE_CHARACTER)); } if (!StringUtils.isEmpty(contextFilter)) { p = cb.and(p, cb.equal(cb.lower(contextPath), contextFilter.toLowerCase())); } p = cb.and(p, cb.notEqual(contextPath, LOCAL_ENV)); return p; }
From source file:com.yunguchang.data.ApplicationRepository.java
@TransactionAttribute(REQUIRES_NEW) public void deleteSchedule(String scheduleId, PrincipalExt principalExt) { applySecurityFilter("applications", principalExt); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TBusScheduleRelaEntity> cq = cb.createQuery(TBusScheduleRelaEntity.class); Root<TBusScheduleRelaEntity> scheduleRoot = cq.from(TBusScheduleRelaEntity.class); cq.where(cb.equal(scheduleRoot.get(TBusScheduleRelaEntity_.uuid), scheduleId)); TBusScheduleRelaEntity relaEntity = Iterables.getFirst(em.createQuery(cq).getResultList(), null); for (TBusApplyinfoEntity applyinfoEntity : relaEntity.getApplications()) { TBusApplyinfoEntity applicationEntity = getApplicationById(applyinfoEntity.getUuid(), principalExt); applicationEntity.setSchedule(null); }/*from ww w. j a va 2s . co m*/ relaEntity.setApplications(null); for (TBusScheduleCarEntity carEntity : relaEntity.getScheduleCars()) { carEntity = em.find(TBusScheduleCarEntity.class, carEntity.getUuid()); em.remove(carEntity); } relaEntity.setScheduleCars(null); em.remove(relaEntity); }
From source file:com.deloitte.smt.service.SignalDetectionService.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public SmtResponse findAllForSearch(SearchDto searchDto) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(); Root<SignalDetection> rootSignalDetection = criteriaQuery.from(SignalDetection.class); Join<SignalDetection, TopicSignalDetectionAssignmentAssignees> joinDetectionAssignees = rootSignalDetection .join("topicSignalDetectionAssignmentAssignees", JoinType.LEFT); //left outer join if (null != searchDto) { Root<Ingredient> rootIngredient = criteriaQuery.from(Ingredient.class); List<Predicate> predicates = new ArrayList<>(10); predicates.add(criteriaBuilder.equal(rootSignalDetection.get("id"), rootIngredient.get(SmtConstant.DETECTION_ID.getDescription()))); addDescription(searchDto, criteriaBuilder, rootSignalDetection, predicates); addFrequency(searchDto, criteriaBuilder, rootSignalDetection, predicates); addIngredients(searchDto, criteriaBuilder, rootIngredient, predicates); addProducts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addLicenses(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addSocs(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addHlts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addHlgts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addPts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addCreatedOrLastRunDate(searchDto, criteriaBuilder, rootSignalDetection, predicates); /**TopicSignalValidationAssignmentAssignees **/ addUserGroupKeys(searchDto, criteriaBuilder, joinDetectionAssignees, rootSignalDetection, predicates); Predicate andPredicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); criteriaQuery.multiselect(rootSignalDetection).where(andPredicate) .orderBy(criteriaBuilder .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription()))) .distinct(true);/* w w w.jav a 2s. co m*/ } else { criteriaQuery.multiselect(rootSignalDetection) .orderBy(criteriaBuilder .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription()))) .distinct(true); } SmtResponse smtResponse = new SmtResponse(); TypedQuery<SignalDetection> q = entityManager.createQuery(criteriaQuery); if (!CollectionUtils.isEmpty(q.getResultList())) { smtResponse.setTotalRecords(q.getResultList().size()); } if (searchDto != null && searchDto.getFetchSize() != 0) { q.setFirstResult(searchDto.getFromRecord()); q.setMaxResults(searchDto.getFetchSize()); smtResponse.setFetchSize(searchDto.getFetchSize()); smtResponse.setFromRecord(searchDto.getFromRecord()); } smtResponse.setResult(q.getResultList()); if (!CollectionUtils.isEmpty(smtResponse.getResult())) { List<SignalDetection> result = (List<SignalDetection>) smtResponse.getResult(); for (SignalDetection signalDetection : result) { signalDetection.setDenominatorForPoisson( denominatorForPoissonRepository.findByDetectionId(signalDetection.getId())); } } return smtResponse; }
From source file:com.yunguchang.data.ApplicationRepository.java
public TBusEvaluateinfoEntity getRateByByApplicationIdAndCarId(String applicationId, String carId, PrincipalExt principalExt) {//from w ww . j av a2 s . c o m applySecurityFilter("applications", principalExt); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TBusEvaluateinfoEntity> cq = cb.createQuery(TBusEvaluateinfoEntity.class); Root<TBusEvaluateinfoEntity> rateRoot = cq.from(TBusEvaluateinfoEntity.class); cq.select(rateRoot); cq.where( cb.equal(rateRoot.get(TBusEvaluateinfoEntity_.application).get(TBusApplyinfoEntity_.uuid), applicationId), cb.equal(rateRoot.get(TBusEvaluateinfoEntity_.car).get(TAzCarinfoEntity_.id), carId)); return Iterables.getFirst(em.createQuery(cq).getResultList(), null); }