sql – org.hibernate.PropertyNotFoundException: Could not find setter for sum on class Class

Question:

Guys, I'm trying to list the best selling products using SQLQuery (if anyone knows of other ways to do it like eg using Criteria, Projections also accepted) with Hibernate, but this error is resulting:

    org.hibernate.PropertyNotFoundException: Could not find setter for sum on class pojo.ItemPedidoVenda

The code:

SQLQuery query = session.createSQLQuery("select sum(quantidade), produto_id from itempedidovenda group by produto_id order by sum(quantidade) desc");
    query.setResultTransformer(Transformers.aliasToBean(ItemPedidoVenda.class));
    List<ItemPedidoVenda> items = query.list();

    return query.list();

Answer:

Using Hibernate Query Language ( HQL ) (or JPQL , I can't tell them apart), you trick the compiler into believing that there is a sum attribute inside ItemPedidoVenda .

To solve this you could either create the attribute and put your getters//setters (because that's what the error is, getSum and setSum is not found) or use native SQL and retrieve from a vector of Object .

I'll leave the description above as that's what's wrong anyway.

What you should notice is that the HQL select sum(quantidade), produto_id from ... will return a Long and the type of the variable that is produto_id , so there is no way to convert this to ItemPedidoVenda . what you can do is run the following HQL SELECT MAX(SUM(ipv.quantidade)), ipv.produto_id FROM ItemPedidoVenda ipv , remove the return ivp.produto and use it in a query onSalesOrder using the object code ( SELECT ipv FROM ItemPedidoVenda ipv WHERE ipv.produto_id = :produtoId ). In code it would look something like this.

query = createQuery("SELECT MAX(SUM(ipv.quantidade)), ipv.produto_id 
    FROM ItemPedidoVenda ipv");
Object[] resultados = query.getResult();
query = createQuery("SELECT ipv FROM ItemPedidoVenda ipv WHERE 
    ipv.produto_id = :produtoId");
query.setParameter(resultados[1]); //Trate aqui caso não tenha nada dentro de resultados;
ItemPedidoVenda objetoEsperado = query.getSingleResult();

It would even work using a subselect within the second select:

SELECT ipv FROM ItemPedidoVenda ipv WHERE ipv.produto_id = (
    SELECT produtoId FROM (
        SELECT MAX(SUM(ipv.quantidade)), ipv.produto_id as produtoId 
        FROM ItemPedidoVenda ipv
    )
)
Scroll to Top