Count with Hibernate Criteria

1

I have two tables, Products and Sales Items In the sales items table I have an FK of products.

I want to 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

Does the following code work?

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();
    
asked by anonymous 08.09.2014 / 05:22

1 answer

1

If in the SalesTables table you have a Product FK (@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 case both the alias and projections use the name of the variables of the "Products" class, remembering that you will get a list of Strings as a return.

    
27.06.2017 / 15:18