List of usage examples for javax.persistence.criteria Root get
<Y> Path<Y> get(SingularAttribute<? super X, Y> attribute);
From source file:com.expressui.core.dao.security.query.UserQuery.java
@Override public List<Predicate> buildCriteria(CriteriaBuilder builder, CriteriaQuery<User> query, Root<User> user) { List<Predicate> predicates = new ArrayList<Predicate>(); if (hasValue(loginName)) { ParameterExpression<String> loginNameExp = builder.parameter(String.class, "loginName"); predicates.add(builder.like(builder.upper(user.<String>get("loginName")), loginNameExp)); }//from w ww . j av a 2 s . c o m if (hasValue(doesNotBelongToRole)) { Subquery<User> subquery = query.subquery(User.class); Root userRole = subquery.from(UserRole.class); ParameterExpression<Role> role = builder.parameter(Role.class, "doesNotBelongToRole"); subquery.select(userRole.get("user")).where(builder.equal(userRole.get("role"), role)); predicates.add(builder.not(user.in(subquery))); } return predicates; }
From source file:com.june.app.board.repository.jpa.BoardRepositoryImpl.java
@Override public long boardListCnt(Board vo) { CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); int bbsId = vo.getBbsId(); CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class); Root<Board> from = countQuery.from(Board.class); countQuery.select(criteriaBuilder.count(from)); if (bbsId > 0) { countQuery.where(criteriaBuilder.equal(from.get("bbsId"), bbsId)); }/*from w ww . j a v a 2 s .co m*/ Long count = em.createQuery(countQuery).getSingleResult(); return count; }
From source file:org.openlmis.fulfillment.repository.custom.impl.OrderRepositoryImpl.java
private Predicate isOneOf(String field, Collection collection, Root<Order> root, Predicate predicate, CriteriaBuilder builder) {/*from w w w . jav a 2 s .c o m*/ return !isEmpty(collection) ? builder.and(predicate, root.get(field).in(collection)) : predicate; }
From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java
/** * @see ??JPA// w w w . j av a 2 s. c o m * @param filters * @param entityClazz * @param isDistinct trueSQLdistinctfalse? * @return */ public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) { return new Specification<T>() { @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (orderParams != null && orderParams.size() > 0) { /* CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class); Root<Foo> from = criteriaQuery.from(Foo.class); CriteriaQuery<Foo> select = criteriaQuery.select(from); criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name"))); */ List<Order> orders = new ArrayList<Order>(orderParams.size()); for (OrderParam orderParam : orderParams) { if (orderParam != null && orderParam.getField() != null) { String fields[] = StringUtil.split(orderParam.getField(), '.'); Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]); for (int i = 1, len = fields.length; i < len; ++i) { expression = expression.get(fields[i]); } if (expression != null) { Order order = (orderParam.getType() == null || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression) : builder.desc(expression); orders.add(order); // query.orderBy(order); } } } query.orderBy(orders); } query.distinct(isDistinct); if (Collections3.isNotEmpty(filters)) { List<Predicate> predicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, Task??"user.name"filedName, ?Task.user.name String[] names = StringUtils.split(filter.fieldName, '.'); Path expression = null; ////// ? boolean hasJoin = names[0].startsWith("[join]"); String fn = hasJoin ? names[0].substring(6) : names[0]; boolean isNotDateType = !(filter.value instanceof Date); try { expression = hasJoin ? root.join(fn) : root.get(fn); if (isNotDateType && isDateType(expression.getJavaType())) { // filter.value?? filter.value = parseDate(filter.value.toString(), filter.operator); } } catch (Exception e) { // logger.error(e.getMessage(), e); continue; // ?? } boolean isPropertyNotValid = false; for (int i = 1; i < names.length; i++) { try { expression = expression.get(names[i]); if (isNotDateType && isDateType(expression.getJavaType())) { filter.value = parseDate(filter.value.toString(), filter.operator); } } catch (Exception e) { // logger.error(e.getMessage(), e); isPropertyNotValid = true; // break; // ?? } } if (expression == null || isPropertyNotValid) { continue; } /////// // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case ORLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.like(expression, "%" + values[i] + "%"); } predicates.add(builder.or(like)); } break; case ANDLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.like(expression, "%" + values[i] + "%"); } predicates.add(builder.and(like)); } break; case ANDNOTLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.notLike(expression, "%" + values[i] + "%"); } predicates.add(builder.and(like)); } break; case OREQ: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.equal(expression, values[i]); } predicates.add(builder.or(like)); } break; case ANDNOTEQ: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.notEqual(expression, values[i]); } predicates.add(builder.and(like)); } break; case NOTEQ: predicates.add(builder.notEqual(expression, (Comparable) filter.value)); break; case NOTLIKE: predicates.add(builder.notLike(expression, "%" + filter.value + "%")); break; case NULL: predicates.add(builder.isNull(expression)); break; case NOTNULL: predicates.add(builder.isNotNull(expression)); break; // case IN: // predicates.add(builder.in(expression).in(values)); // break; } } // ? and ??? if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } } return builder.conjunction(); } }; }
From source file:com.vladmihalcea.HibernateFetchStrategyTest.java
@Test public void test() { final Long productId = transactionTemplate.execute(new TransactionCallback<Long>() { @Override// w ww. ja v a 2s . co m public Long doInTransaction(TransactionStatus transactionStatus) { Company company = new Company(); company.setName("TV Company"); entityManager.persist(company); Product product = new Product("tvCode"); product.setName("TV"); product.setCompany(company); Image frontImage = new Image(); frontImage.setName("front image"); frontImage.setIndex(0); Image sideImage = new Image(); sideImage.setName("side image"); sideImage.setIndex(1); product.addImage(frontImage); product.addImage(sideImage); WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo(); warehouseProductInfo.setQuantity(101); product.addWarehouse(warehouseProductInfo); Importer importer = new Importer(); importer.setName("Importer"); entityManager.persist(importer); product.setImporter(importer); entityManager.persist(product); return product.getId(); } }); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { LOG.info("Fetch using find"); Product product = entityManager.find(Product.class, productId); assertNotNull(product); return null; } }); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { LOG.info("Fetch using JPQL"); Product product = entityManager .createQuery("select p " + "from Product p " + "where p.id = :productId", Product.class) .setParameter("productId", productId).getSingleResult(); assertNotNull(product); return null; } }); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { LOG.info("Fetch using Criteria"); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Product> cq = cb.createQuery(Product.class); Root<Product> productRoot = cq.from(Product.class); cq.where(cb.equal(productRoot.get("id"), productId)); Product product = entityManager.createQuery(cq).getSingleResult(); assertNotNull(product); return null; } }); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { LOG.info("Fetch using join fetch JPQL"); Product product = product = entityManager.createQuery("select p " + "from Product p " + "inner join fetch p.warehouseProductInfo " + "inner join fetch p.importer", Product.class) .getSingleResult(); assertNotNull(product); return null; } }); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { Image image = entityManager .createQuery("select i " + "from Image i " + "inner join fetch i.product p " + "where p.id = :productId", Image.class) .setParameter("productId", productId).getResultList().get(0); assertNotNull(image); return null; } }); }
From source file:org.openlmis.fulfillment.repository.custom.impl.OrderRepositoryImpl.java
private Predicate isEqual(String field, Object value, Root<Order> root, Predicate predicate, CriteriaBuilder builder) {//from w ww. ja va 2 s . co m return value != null ? builder.and(predicate, builder.equal(root.get(field), value)) : predicate; }
From source file:org.apereo.lap.dao.RiskConfidenceRepositoryImpl.java
public List<RiskConfidence> findByUserCourseDate(final String user, final String course) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<RiskConfidence> criteria = builder.createQuery(RiskConfidence.class); Root<RiskConfidence> root = criteria.from(RiskConfidence.class); EntityType<RiskConfidence> type = entityManager.getMetamodel().entity(RiskConfidence.class); criteria.orderBy(builder.desc(root.get("dateCreated"))); List<RiskConfidence> lastRiskConfidences = entityManager.createQuery(criteria).setFirstResult(0) .setMaxResults(1).getResultList(); if (lastRiskConfidences == null || lastRiskConfidences.isEmpty()) { logger.warn("No risk confidence records found"); return new ArrayList<RiskConfidence>(); }/* www . j ava2 s . c o m*/ RiskConfidence lastRickConfidence = lastRiskConfidences.get(0); builder = entityManager.getCriteriaBuilder(); criteria = builder.createQuery(RiskConfidence.class); root = criteria.from(RiskConfidence.class); type = entityManager.getMetamodel().entity(RiskConfidence.class); Predicate groupPredicate = builder.equal(root.get("groupId"), lastRickConfidence.getGroupId()); if (!StringUtils.isEmpty(user) && !StringUtils.isEmpty(course)) { criteria.where(groupPredicate, builder.equal( builder.lower( root.get(type.getDeclaredSingularAttribute("alternativeId", String.class))), user.toLowerCase()), builder.equal( builder.lower(root.get(type.getDeclaredSingularAttribute("courseId", String.class))), course.toLowerCase())); } else if (!StringUtils.isEmpty(user)) { criteria.where(groupPredicate, builder.equal( builder.lower( root.get(type.getDeclaredSingularAttribute("alternativeId", String.class))), user.toLowerCase())); } else if (!StringUtils.isEmpty(course)) { criteria.where(groupPredicate, builder.equal( builder.lower(root.get(type.getDeclaredSingularAttribute("courseId", String.class))), course.toLowerCase())); } else { criteria.where(groupPredicate); } return entityManager.createQuery(criteria).getResultList(); }
From source file:com.aimdek.ccm.dao.impl.TransactionRepositoryImpl.java
/** * {@inheritDoc}// w w w .j a va 2 s . c o m */ public Transaction findLastTransaction() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Transaction> query = builder.createQuery(Transaction.class); Root<Transaction> root = query.from(Transaction.class); query.select(root); query.orderBy(builder.desc(root.get(FIELD_CONSTANT_TRANSACTION_ID))); try { return entityManager.createQuery(query).setMaxResults(1).getSingleResult(); } catch (NoResultException e) { LOGGER.error("Error while retrieving last transaction", e); } return null; }
From source file:net.dontdrinkandroot.persistence.dao.TypedJpaDao.java
@Override @Transactional(propagation = Propagation.MANDATORY, readOnly = true) public List<E> findAll(final SingularAttribute<? super E, ?> attribute, final boolean asc, final int firstResult, final int maxResults) { final CriteriaBuilder builder = this.getCriteriaBuilder(); final CriteriaQuery<E> criteriaQuery = builder.createQuery(this.entityClass); final Root<E> from = criteriaQuery.from(this.entityClass); if (attribute != null) { if (asc) { criteriaQuery.orderBy(builder.asc(from.get(attribute))); } else {/*from w w w . j a v a 2s .c o m*/ criteriaQuery.orderBy(builder.desc(from.get(attribute))); } } return this.find(criteriaQuery, firstResult, maxResults); }
From source file:org.osiam.resource_server.storage.dao.ResourceDao.java
public <T extends ResourceEntity> SearchResult<T> search(Class<T> clazz, ParseTree filterTree, int count, int startIndex, String sortBy, String sortOrder, FilterParser<T> filterParser) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<T> resourceQuery = cb.createQuery(clazz); Root<T> resourceRoot = resourceQuery.from(clazz); Subquery<Long> internalIdQuery = resourceQuery.subquery(Long.class); Root<T> internalIdRoot = internalIdQuery.from(clazz); internalIdQuery.select(internalIdRoot.get(ResourceEntity_.internalId)); if (filterTree != null && filterTree.getChildCount() > 0) { Predicate predicate = filterParser.createPredicateAndJoin(filterTree, internalIdRoot); internalIdQuery.where(predicate); }/*from ww w. j a v a 2 s.co m*/ resourceQuery.select(resourceRoot) .where(cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery)); // TODO: evaluate if a User-/GroupDao supplied default sortBy field is possible Expression<?> sortByField = resourceRoot.get(ResourceEntity_.id); if (sortBy != null && !sortBy.isEmpty()) { sortByField = filterParser.createSortByField(sortBy, resourceRoot); } // default order is ascending Order order = cb.asc(sortByField); if (sortOrder.equalsIgnoreCase("descending")) { order = cb.desc(sortByField); } resourceQuery.orderBy(order); TypedQuery<T> query = em.createQuery(resourceQuery); query.setFirstResult(startIndex); query.setMaxResults(count); List<T> results = query.getResultList(); long totalResult = getTotalResults(clazz, internalIdQuery); return new SearchResult<>(results, totalResult); }