List of usage examples for javax.persistence.criteria CriteriaQuery select
CriteriaQuery<T> select(Selection<? extends T> selection);
From source file:org.apache.openejb.util.proxy.QueryProxy.java
private <T> Query createFinderQuery(final EntityManager entityManager, final String methodName, final Class<T> entityType, final Object[] args) { final List<String> conditions = parseMethodName(methodName); final EntityType<T> et = entityManager.getMetamodel().entity(entityType); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Object> query = cb.createQuery(); final Root<T> from = query.from(entityType); query = query.select(from); int i = 0;/*from w w w . ja v a 2 s . co m*/ Predicate where = null; for (final String condition : conditions) { final SingularAttribute<? super T, ?> attribute = et.getSingularAttribute(condition); final Path<?> path = from.get(attribute); final Class<?> javaType = attribute.getType().getJavaType(); final Predicate currentClause; if (javaType.equals(String.class)) { currentClause = cb.like((Expression<String>) path, (String) args[i++]); } else if (Number.class.isAssignableFrom(javaType) || javaType.isPrimitive()) { currentClause = cb.equal(path, args[i++]); } else { LOGGER.warning("field " + condition + " not found, ignoring"); continue; } if (where == null) { where = currentClause; } else { where = cb.and(where, currentClause); } } if (where != null) { query = query.where(where); } // pagination final TypedQuery<?> emQuery = entityManager.createQuery(query); if (args != null && args.length == conditions.size() + 2 && isInt(args[args.length - 2].getClass()) && isInt(args[args.length - 1].getClass())) { final int first = (Integer) args[args.length - 2]; final int max = (Integer) args[args.length - 1]; emQuery.setFirstResult(first); emQuery.setMaxResults(max); } return emQuery; }
From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java
/** * count entity by ParamInfo// ww w . ja v a2s . co 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(); }
From source file:org.broadleafcommerce.core.order.dao.OrderDaoImpl.java
@Override public List<Order> readOrdersByIds(List<Long> orderIds) { if (orderIds == null || orderIds.size() == 0) { return null; }//w w w. j ava 2s . co m if (orderIds.size() > 100) { LOG.warn("Not recommended to use the readOrdersByIds method for long lists of orderIds, since " + "Hibernate is required to transform the distinct results. The list of requested" + "order ids was (" + orderIds.size() + ") in length."); } CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Order> criteria = builder.createQuery(Order.class); Root<OrderImpl> order = criteria.from(OrderImpl.class); criteria.select(order); // We only want results that match the order IDs criteria.where(order.get("id").as(Long.class).in(orderIds)); TypedQuery<Order> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Order"); return query.getResultList(); }
From source file:org.broadleafcommerce.core.order.dao.OrderDaoImpl.java
@Override public List<Order> readBatchOrders(int start, int pageSize, List<OrderStatus> statuses) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Order> criteria = builder.createQuery(Order.class); Root<OrderImpl> order = criteria.from(OrderImpl.class); criteria.select(order); if (CollectionUtils.isNotEmpty(statuses)) { // We only want results that match the orders with the correct status ArrayList<String> statusStrings = new ArrayList<String>(); for (OrderStatus status : statuses) { statusStrings.add(status.getType()); }/*from w ww . j a v a 2s . com*/ criteria.where(order.get("status").as(String.class).in(statusStrings)); } TypedQuery<Order> query = em.createQuery(criteria); query.setFirstResult(start); query.setMaxResults(pageSize); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Order"); return query.getResultList(); }
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. * /*w w w . j ava 2 s. c om*/ * @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:eu.uqasar.service.ProcessService.java
public long countAllFiltered(final ProcessesFilterStructure filter) { logger.infof("counting all Processes matching the filter %s ...", filter); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> criteria = cb.createQuery(Long.class); Root<Process> from = criteria.from(Process.class); List<Predicate> predicates = getFilterPredicates(filter, cb, from); if (!predicates.isEmpty()) { criteria.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); }//from w w w. java 2 s.co m criteria.select(cb.countDistinct(from)); return em.createQuery(criteria).getSingleResult(); }
From source file:org.synyx.hades.dao.orm.GenericJpaDao.java
/** * Creates a new {@link TypedQuery} from the given {@link Specification}. * /*from w w w. j a v a2 s. c o m*/ * @param spec can be {@literal null} * @param pageable can be {@literal null} * @return */ private TypedQuery<T> getQuery(Specification<T> spec, Pageable pageable) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> query = builder.createQuery(getDomainClass()); Root<T> root = applySpecificationToCriteria(spec, query); query.select(root); if (pageable != null) { query.orderBy(toOrders(pageable.getSort(), root, builder)); } return getEntityManager().createQuery(query); }
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. * /*w w w . j a v a 2 s . 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:eu.uqasar.service.AbstractService.java
/** * Method to get the entity of class by a given name. * @param clazz Class//from w ww. j a va 2 s . c o m * @param name attribute name of the searched entity * @return T entity */ public <T extends Persistable> T getByName(Class<T> clazz, String name) { logger.infof("loading %s with name %d ...", getReadableClassName(clazz), name); T entity = null; CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(clazz); Root<T> ent = criteriaQuery.from(clazz); criteriaQuery.select(ent).where(criteriaBuilder.equal(ent.get("name"), name)); List<T> entities = em.createQuery(criteriaQuery).getResultList(); if (entities != null && entities.size() > 0) { entity = entities.get(0); } return entity; }
From source file:org.jnap.core.persistence.jpa.DaoSupport.java
@Override public boolean exists(Serializable id) { CriteriaBuilder builder = getCriteriaBuilder(); CriteriaQuery<Long> count = builder.createQuery(Long.class); Root<?> root = count.from(getEntityClass()); count.select(builder.count(root)); count.where(builder.equal(root.get("id"), id)); return entityManager.createQuery(count).getSingleResult() == 1; }