How to get the count and objects with jpa criteria?

Asked

Viewed 24 times

2

need to return the grouping results and also the number of each item of a query with criteria jpa.

public List<Dica> obterDicaPorUsuario(){
    final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); 
    final CriteriaQuery<Dica> cQuery = cb.createQuery(Dica.class);
    final Root<Dica> root = cQuery.from(Dica.class);

    List<Predicate> condicoes = new ArrayList<Predicate>();

    Expression<Usuario> EpDescricao = root.get("usuario");

   cQuery.groupBy(root.get("usuario")); 
   cQuery.orderBy(cb.desc(cb.count(root.get("usuario"))));

    cQuery.select(root).where(condicoes.toArray(new Predicate[]{}));

    List<Dica> list = getEntityManager().createQuery(cQuery).getResultList();
    for (Dica dica : list) {
        System.out.println(" - -  " +dica.getUsuario().getNome() );

    } 

    return list;

}

This grouping perfectly, but I also need to return how much of each grouping was made. If anyone knows a better way to do that, I’d appreciate it.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.