List of usage examples for javax.persistence.criteria CriteriaBuilder createQuery
<T> CriteriaQuery<T> createQuery(Class<T> resultClass);
CriteriaQuery
object with the specified result type. From source file:com.aimdek.ccm.dao.impl.UserRepositoryImpl.java
/** * {@inheritDoc}//from w w w . j ava 2 s . c o m */ public User findLastCustomer() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<User> query = builder.createQuery(User.class); Root<User> root = query.from(User.class); query.select(root); query.where(builder.equal(root.<String>get(FIELDCONSTANT_USER_ROLE), ROLE_CUSTOMER)); query.orderBy(builder.desc(root.get(FIELD_CONSTANT_CREATED_AT))); try { return entityManager.createQuery(query).setMaxResults(1).getSingleResult(); } catch (NoResultException e) { LOGGER.error("Error while retrieving last customer", e); } return null; }
From source file:gov.gtas.repository.CaseDispositionRepositoryImpl.java
@Override public Pair<Long, List<Case>> findByCriteria(CaseRequestDto dto) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Case> q = cb.createQuery(Case.class); Root<Case> root = q.from(Case.class); List<Predicate> predicates = new ArrayList<>(); TypedQuery<Case> typedQuery = em.createQuery(q); // sorting/*from w w w . j a va 2s .c o m*/ if (dto.getSort() != null) { List<Order> orders = new ArrayList<>(); for (SortOptionsDto sort : dto.getSort()) { Expression<?> e = root.get(sort.getColumn()); Order order; if ("desc".equalsIgnoreCase(sort.getDir())) { order = cb.desc(e); } else { order = cb.asc(e); } orders.add(order); } q.orderBy(orders); } if (dto.getFlightId() != null) { predicates.add(cb.equal(root.<Long>get("flightId"), dto.getFlightId())); } if (dto.getPaxId() != null) { predicates.add(cb.equal(root.<Long>get("paxId"), dto.getPaxId())); } if (dto.getPaxName() != null) { String likeString = String.format("%%%s%%", dto.getPaxName().toUpperCase()); predicates.add(cb.like(root.<String>get("paxName"), likeString)); } if (dto.getLastName() != null) { // map this to full pax name String likeString = String.format("%%%s%%", dto.getLastName().toUpperCase()); predicates.add(cb.like(root.<String>get("paxName"), likeString)); } if (dto.getStatus() != null) { String likeString = String.format("%%%s%%", dto.getStatus().toUpperCase()); predicates.add(cb.like(root.<String>get("status"), likeString)); } if (dto.getFlightNumber() != null) { predicates.add(cb.equal(root.<Long>get("flightNumber"), dto.getFlightNumber())); } if (dto.getRuleCatId() != null) { predicates.add(cb.equal(root.<Long>get("highPriorityRuleCatId"), dto.getRuleCatId())); } Predicate etaCondition; if (dto.getEtaStart() != null && dto.getEtaEnd() != null) { Path<Date> eta = root.<Date>get("flightETADate"); Predicate startPredicate = cb.or(cb.isNull(eta), cb.greaterThanOrEqualTo(eta, dto.getEtaStart())); Predicate endPredicate = cb.or(cb.isNull(eta), cb.lessThanOrEqualTo(eta, dto.getEtaEnd())); etaCondition = cb.and(startPredicate, endPredicate); predicates.add(etaCondition); } q.select(root).where(predicates.toArray(new Predicate[] {})); typedQuery = em.createQuery(q); // total count CriteriaQuery<Long> countQuery = cb.createQuery(Long.class); countQuery.select(cb.count(countQuery.from(Case.class))).where(predicates.toArray(new Predicate[] {})); Long count = em.createQuery(countQuery).getSingleResult(); // pagination int pageNumber = dto.getPageNumber(); int pageSize = dto.getPageSize(); int firstResultIndex = (pageNumber - 1) * pageSize; typedQuery.setFirstResult(firstResultIndex); typedQuery.setMaxResults(dto.getPageSize()); logger.debug(typedQuery.unwrap(org.hibernate.Query.class).getQueryString()); List<Case> results = typedQuery.getResultList(); return new ImmutablePair<>(count, results); }
From source file:net.shopxx.dao.impl.ArticleDaoImpl.java
public Page<Article> findPage(ArticleCategory articleCategory, Tag tag, Boolean isPublication, Pageable pageable) {/*from ww w.j av a 2 s .c om*/ CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class); Root<Article> root = criteriaQuery.from(Article.class); criteriaQuery.select(root); Predicate restrictions = criteriaBuilder.conjunction(); if (articleCategory != null) { Subquery<ArticleCategory> subquery = criteriaQuery.subquery(ArticleCategory.class); Root<ArticleCategory> subqueryRoot = subquery.from(ArticleCategory.class); subquery.select(subqueryRoot); subquery.where(criteriaBuilder.or(criteriaBuilder.equal(subqueryRoot, articleCategory), criteriaBuilder.like(subqueryRoot.<String>get("treePath"), "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId() + ArticleCategory.TREE_PATH_SEPARATOR + "%"))); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.in(root.get("articleCategory")).value(subquery)); } if (tag != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.join("tags"), tag)); } if (isPublication != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isPublication"), isPublication)); } criteriaQuery.where(restrictions); if (pageable == null || ((StringUtils.isEmpty(pageable.getOrderProperty()) || pageable.getOrderDirection() == null) && CollectionUtils.isEmpty(pageable.getOrders()))) { criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")), criteriaBuilder.desc(root.get("createDate"))); } return super.findPage(criteriaQuery, pageable); }
From source file:com.aimdek.ccm.dao.impl.UserRepositoryImpl.java
/** * {@inheritDoc}//from w w w .ja va 2 s . c om */ public List<User> getCustomers(int start, int limit, String sortField, String sortOrder, Map<String, Object> filters) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<User> query = builder.createQuery(User.class); Root<User> root = query.from(User.class); Predicate isCustomerRole = builder.equal(root.get(FIELDCONSTANT_USER_ROLE), ROLE_CUSTOMER); Predicate hasCreditCard = builder.equal(root.get(FIELD_CONSTANT_HAS_CREDIT_CARD), TRUE); query.where(builder.and(isCustomerRole, hasCreditCard)); query.select(root); addSorting(sortField, sortOrder, query, builder, root); addFilterCriteria(filters, builder, root, query); return entityManager.createQuery(query).setFirstResult(start).setMaxResults(limit).getResultList(); }
From source file:com.devicehive.dao.rdbms.DeviceDaoRdbmsImpl.java
@Override public List<DeviceVO> list(String name, String namePattern, Long networkId, String networkName, Long deviceClassId, String deviceClassName, String sortField, @NotNull Boolean sortOrderAsc, Integer take, Integer skip, HivePrincipal principal) { final CriteriaBuilder cb = criteriaBuilder(); final CriteriaQuery<Device> criteria = cb.createQuery(Device.class); final Root<Device> from = criteria.from(Device.class); final Predicate[] predicates = CriteriaHelper.deviceListPredicates(cb, from, ofNullable(name), ofNullable(namePattern), ofNullable(networkId), ofNullable(networkName), ofNullable(deviceClassId), ofNullable(deviceClassName), ofNullable(principal)); criteria.where(predicates);/*from w w w .j a v a 2 s .c om*/ CriteriaHelper.order(cb, criteria, from, ofNullable(sortField), sortOrderAsc); final TypedQuery<Device> query = createQuery(criteria); cacheQuery(query, of(CacheConfig.refresh())); ofNullable(take).ifPresent(query::setMaxResults); ofNullable(skip).ifPresent(query::setFirstResult); List<Device> resultList = query.getResultList(); return resultList.stream().map(Device::convertToVo).collect(Collectors.toList()); }
From source file:org.jboss.quickstarts.wfk.contact.ContactRepository.java
/** * Find just one Contact by the first name that is passed in. If there is more then one, only the first will be returned. * //www . ja v a 2s . co m * @param firstName * @return Contact */ Contact findByFirstName(String firstName) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Contact> criteria = cb.createQuery(Contact.class); Root<Contact> contact = criteria.from(Contact.class); // Swap criteria statements if you would like to try out type-safe criteria queries, a new feature in JPA 2.0. // criteria.select(contact).where(cb.equal(contact.get(Contact_.firstName), firstName)); criteria.select(contact).where(cb.equal(contact.get("firstName"), firstName)); return em.createQuery(criteria).getSingleResult(); }
From source file:org.jboss.quickstarts.wfk.contact.ContactRepository.java
/** * Find just one Contact by the last name that is passed in. If there is more then one, only the first will be returned. * // ww w. ja va 2s. com * @param lastName * @return Contact */ Contact findByLastName(String lastName) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Contact> criteria = cb.createQuery(Contact.class); Root<Contact> contact = criteria.from(Contact.class); // Swap criteria statements if you would like to try out type-safe criteria queries, a new feature in JPA 2.0. // criteria.select(contact).where(cb.equal(contact.get(Contact_.lastName), lastName)); criteria.select(contact).where(cb.equal(contact.get("lastName"), lastName)); return em.createQuery(criteria).getSingleResult(); }
From source file:org.oncoblocks.centromere.jpa.CentromereJpaRepository.java
/** * Returns a unsorted list of distinct values of the requested field. * * @param field Model field name./*from w ww . j a v a 2 s.co m*/ * @return Sorted list of distinct values of {@code field}. */ public Iterable<Object> distinct(String field) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<T> query = builder.createQuery(metadata.getJavaType()); Root<T> root = query.from(metadata.getJavaType()); query.select(root.get(field)).distinct(true); return (List) entityManager.createQuery(query).getResultList(); }
From source file:net.dontdrinkandroot.persistence.dao.TypedJpaDao.java
@Override @Transactional(propagation = Propagation.MANDATORY, readOnly = true) public List<E> findAll(final PredicateBuilder<E> filter) { final CriteriaBuilder builder = this.getCriteriaBuilder(); final CriteriaQuery<E> criteriaQuery = builder.createQuery(this.entityClass); final Root<E> from = criteriaQuery.from(this.entityClass); criteriaQuery.where(filter.createPredicate(builder, from)); return this.find(criteriaQuery); }
From source file:org.oncoblocks.centromere.jpa.CentromereJpaRepository.java
/** * Returns a unsorted list of distinct values of the requested field, filtered using a {@link QueryCriteria} * based query.//from w w w. ja v a2 s .com * * @param field Model field name. * @param queryCriterias Query criteria to filter the field values by. * @return Sorted list of distinct values of {@code field}. */ public Iterable<Object> distinct(String field, Iterable<QueryCriteria> queryCriterias) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<T> query = builder.createQuery(metadata.getJavaType()); Root<T> root = query.from(metadata.getJavaType()); query.where(queryBuilder.createSpecification(queryCriterias).toPredicate(root, query, builder)); query.select(root.get(field)).distinct(true); return (List) entityManager.createQuery(query).getResultList(); }