Developer404
Developer404

Reputation: 5972

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

Upvotes: 0

Views: 1878

Answers (2)

JB Nizet
JB Nizet

Reputation: 691973

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.

Upvotes: 0

axtavt
axtavt

Reputation: 242726

You can create an appropriate constructor for your POJO and then use constructor syntax:

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

Upvotes: 1

Related Questions