Search code examples
hibernatepojo

How to map count query to pojo class?


I'm trying to execute the query which returns a count of the employees and the department id. How can I assign to pojo. And how to retrieve the resultset from query using hibernate? See my code below:

select e.depid, count(empid) from empwithdep e,
   dept d  where e.depid=d.depid group by e.depid order by e.depid

Solution

  • When a query returns projections rather than entities, the returned list is a List<Object[]>. Each Object[] contains the columns returned by the query:

    List<Object[]> rows = query.list();
    for (Object[] row : rows) {
        Long depId = (Long) row[0];
        Long count = (Long) row[1];
        // create a POJO using depId and count...
    }
    

    This is described in the documentation.