Example usage for javax.persistence.criteria CriteriaQuery from

List of usage examples for javax.persistence.criteria CriteriaQuery from

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery from.

Prototype

<X> Root<X> from(Class<X> entityClass);

Source Link

Document

Create and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.

Usage

From source file:de.ks.idnadrev.information.view.InformationOverviewDS.java

private List<InformationPreviewItem> getResults(String name, List<String> tagNames, Category category,
        EntityManager em, CriteriaBuilder builder, Class<? extends Information<?>> clazz) {
    CriteriaQuery<InformationPreviewItem> query = builder.createQuery(InformationPreviewItem.class);
    Root<? extends Information<?>> root = query.from(clazz);

    ArrayList<Predicate> filters = new ArrayList<>();
    if (!name.isEmpty()) {
        filters.add(builder.like(builder.lower(root.<String>get(KEY_NAME)), name));
    }/*from   w  ww.  ja  va  2  s .  co  m*/
    if (!tagNames.isEmpty()) {
        List<Tag> tags = getTags(tagNames, em);
        SetJoin<TextInfo, Tag> tagJoin = root.joinSet(KEY_TAGS);
        filters.add(tagJoin.in(tags));
    }
    if (category != null) {
        filters.add(builder.equal(root.get(KEY_CATEGORY), category));
    }
    query.distinct(true);

    query.where(filters.toArray(new Predicate[filters.size()]));
    query.select(
            builder.construct(InformationPreviewItem.class, root.get(KEY_NAME), root.get(KEY_CREATIONTIME)));
    List<InformationPreviewItem> resultList = em.createQuery(query).getResultList();
    return resultList;
}

From source file:com.sapito.db.dao.AbstractDao.java

/**
 * Obtiene todos los registros para una entidad dada ordenados con los
 * criterios establecidos a traves de la lista <code>ordering</code>
 * //from   w w w  .jav a 2 s .c  o  m
 * @param ordering : ["fieldName", "ASC" | "DESC"] <br>
 *                   (if != "ASC" se utiliza "DESC" por default)
 * 
 * @return Registros recuperados ordenados mediante los criterios dados
 */
public List<T> findAll(LinkedHashMap<String, String> ordering) {
    CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
    Root<T> root = cq.from(entityClass);
    cq.select(root);

    if (ordering != null) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        Set<String> set = ordering.keySet();
        List<Order> orders = new ArrayList<>();
        for (String orderingField : set) {
            Order order = (ordering.get(orderingField).equals("ASC")) ? cb.asc(root.get(orderingField))
                    : cb.desc(root.get(orderingField));
            orders.add(order);
        }

        cq.orderBy(orders);
    }

    return entityManager.createQuery(cq).setMaxResults(MAX_RECORDS_RETURNED).getResultList();
}

From source file:net.groupbuy.dao.impl.MessageDaoImpl.java

public Page<Message> findPage(Member member, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Message> criteriaQuery = criteriaBuilder.createQuery(Message.class);
    Root<Message> root = criteriaQuery.from(Message.class);
    criteriaQuery.select(root);/*w  w w  . ja va  2s .  c  om*/
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNull(root.get("forMessage")),
            criteriaBuilder.equal(root.get("isDraft"), false));
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(
                        criteriaBuilder.and(criteriaBuilder.equal(root.get("sender"), member),
                                criteriaBuilder.equal(root.get("senderDelete"), false)),
                        criteriaBuilder.and(criteriaBuilder.equal(root.get("receiver"), member),
                                criteriaBuilder.equal(root.get("receiverDelete"), false))));
    } else {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(
                        criteriaBuilder.and(criteriaBuilder.isNull(root.get("sender")),
                                criteriaBuilder.equal(root.get("senderDelete"), false)),
                        criteriaBuilder.and(criteriaBuilder.isNull(root.get("receiver")),
                                criteriaBuilder.equal(root.get("receiverDelete"), false))));
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);

}

From source file:dao.jpa.TestJpaDao.java

@Test
@Transactional//from   www  .  j  a  va  2  s . co m
public void testCopy() {
    EntityManager em = bookDao.getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Book> criteria = cb.createQuery(Book.class);

    // Fetch join
    Root<Book> root = criteria.from(Book.class);
    Path<String> path = root.join("author").<String>get("name");
    root.fetch("author");
    criteria.select(root);

    // SubQuery
    Subquery<String> sq = criteria.subquery(String.class);
    Root<Author> author = sq.from(Author.class);
    sq.select(author.<String>get("name"));
    sq.where(cb.equal(author.<String>get("name"), "Rod"));

    criteria.where(cb.in(path).value(sq));

    CriteriaQuery<Book> copy = cb.createQuery(Book.class);
    JpaUtils.copyCriteria(criteria, copy);

    List<Book> copyBooks = em.createQuery(copy).getResultList();
    List<Book> books = em.createQuery(criteria).getResultList();
    assertEquals(books, copyBooks);
}

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:se.kth.csc.persist.JPAStore.java

@Override
public Queue fetchQueueWithName(String name) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Queue> q = cb.createQuery(Queue.class);
    Root<Queue> queue = q.from(Queue.class);
    try {/*from  w  w w.  j  a  v  a  2  s  .  c o  m*/
        return entityManager.createQuery(q.select(queue).where(cb.equal(queue.get(Queue_.name), name)))
                .getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:ispok.dao.TournamentHibernateJpaDao.java

@Override
public List<Tournament> getPage(int first, int rows, String sortBy, boolean ascending,
        Map<String, Object> filters) {

    //        Session session = getEntityManager().unwrap(Session.class);
    //        Criteria criteria = session.createCriteria(Tournament.class);
    //        CriteriaBuilder cb = entityManagerfactory.getCriteriaBuilder();
    //        CriteriaQuery<Tournament> cq = cb.createQuery(Tournament.class);
    //        Root<Tournament> tou = cq.from(Tournament.class);
    //        cb.para
    //        criteria.add(cb.equal(tou, tou))
    //        String queryString = "SELECT e FROM " + Tournament.class.getSimpleName();
    //        if (!filters.isEmpty()) {
    //            queryString += " WHERE ";
    //            for (Map.Entry<String, Object> entry : filters.entrySet()) {
    //                if ("id".equals(entry.getKey())) {
    //                    queryString += "e." + entry.getKey() + " = " + entry.getValue();
    //                } else {
    //                    queryString += "e." + entry.getKey() + " LIKE '" + entry.getValue() + "'";
    //                }
    //            }
    //        }/*from ww  w  . j av a  2  s  .c o  m*/
    //                " e WHERE e." + property + " = :value";
    //        return getEntityManager().createQuery(queryString).setParameter("value", value).getResultList();
    //        return null;
    //        Session session = getEntityManager().unwrap(Session.class);
    //        Criteria criteria = session.createCriteria(Tournament.class);
    //
    //        for (Map.Entry<String, Object> filter : filters.entrySet()) {
    //            if ("id".equals(filter.getKey())) {
    //                criteria.add(Restrictions.eq("id", Long.parseLong(filter.getValue().toString())));
    //            } else {
    //                criteria.add(Restrictions.ilike(filter.getKey(), (String) filter.getValue(), MatchMode.START));
    //            }
    //        }
    //
    //        if (ascending) {
    //            criteria.addOrder(Order.asc(sortBy));
    //        } else {
    //            criteria.addOrder(Order.desc(sortBy));
    //        }
    //
    //        criteria.setFirstResult(first);
    //        criteria.setMaxResults(rows);
    //
    //        criteria.setResultTransformer(Transformers.aliasToBean(clazz));
    //        List<ENTITY> list = criteria.list();
    //
    //        return list;
    EntityManager em = getEntityManager();

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Tournament> cq = cb.createQuery(Tournament.class);
    Root<Tournament> t = cq.from(Tournament.class);

    cq.select(t);

    TypedQuery<Tournament> tq = em.createQuery(cq);

    List<Tournament> tournaments = tq.getResultList();
    return tournaments;

}

From source file:net.dontdrinkandroot.persistence.dao.ExampleGeneratedIdEntityDaoImpl.java

@Override
@Transactional(readOnly = true)//from  w  w w. j  a  v a  2 s  .c  o  m
public List<ExampleGeneratedIdEntity> findByOtherText(final String text) {
    final CriteriaBuilder builder = this.getCriteriaBuilder();
    final CriteriaQuery<ExampleGeneratedIdEntity> criteriaQuery = builder.createQuery(this.entityClass);
    criteriaQuery.distinct(true);
    final Root<ExampleGeneratedIdEntity> root = criteriaQuery.from(this.entityClass);

    final ListJoin<ExampleGeneratedIdEntity, ExampleIdEntity> join = root
            .join(ExampleGeneratedIdEntity_.otherEntities);

    criteriaQuery.where(builder.equal(join.get(ExampleIdEntity_.text), text));

    return this.find(criteriaQuery);
}

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 CriteriaBuilder builder = this.getCriteriaBuilder();
    final CriteriaQuery<E> criteriaQuery = builder.createQuery(this.entityClass);
    final Root<E> from = criteriaQuery.from(this.entityClass);

    if (asc) {/*from   w  w  w . j a  v a 2s.c om*/
        criteriaQuery.orderBy(builder.asc(from.get(attribute)));
    } else {
        criteriaQuery.orderBy(builder.desc(from.get(attribute)));
    }

    return this.find(criteriaQuery);
}

From source file:com.fantasy.stataggregator.entities.dao.AbstractRepository.java

public int count() {
    javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
    cq.select(em.getCriteriaBuilder().count(rt));
    javax.persistence.Query q = em.createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
}