Count with Hibernate Criteria

Asked

Viewed 989 times

1

I have two tables, Products and Itensvenda In the itensvenda table I have a FK of products.

I want to make the following query using Hibernate criteria.

select count(itensvenda.prdcodigo), produtos.prddescricao  from itensvenda 
inner join produtos on itensvenda.prdcodigo = produtos .prdcodigo
group by itensvenda.prdcodigo, produtos.prddescricao

the following code works?

Criteria c = session.createCriteria();
c.createAlias("prdcodigo", "prdcodigo");
c.setProjection(Projections.count("prdcodigo.prdcodigo"));
c.setProjection(Projections.property("prdcodigo.prddescricao"));
c.setProjection(Projections.groupProperty("prdcodigo.prdcodigo"));
c.setProjection(Projections.groupProperty("prdcodigo.prddescricao"));
return c.list();
  • 1

    Guilherme, can’t test your code? If you can enable the query log in your DataSource and see if it looks the same. In Criteria you should not specify the table name and its attributes, but the class name and its fields (The JPA implementation you are using will translate from class to table). And the class isn’t missing Produtos and the inner join with the ItensVenda?

  • The code I posted didn’t work. ?

1 answer

1


If in the Itensvenda table you have a FK of Products (@Manytoone as I understand it) you can do the following using Detachedcriteria.

DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ItensVenda.class);
detachedCriteria.createAlias("produtos", "produtos");
detachedCriteria.setProjection(Projections.property("produtos.descricao"));
detachedCriteria.setProjection(Projections.groupProperty("produtos.codigo"));
detachedCriteria.setProjection(Projections.groupProperty("produtos.descricao"));
detachedCriteria.getExecutableCriteria(session).list();

In the case both the alias when the projections use the name of the class variables "Products", remembering that you will get as return a list of Strings.

Browser other questions tagged

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