When using the following JPQL, I get n+1 queries executed:
Code:
List resultList = em.createQuery("select new com.example.dto.CountableEntryDto(p, count(dogs)) from Person p left join p.dogs dogs group by p.id").getResultList();
results in:
Code:
select person0_.id as col_0_0_, count(dogs1_.id) as col_1_0_ from Person person0_ left outer join Dog dogs1_ on person0_.id=dogs1_.owner_id group by person0_.id
select person0_.id as id32_0_, person0_.age as age32_0_, person0_.firstname as firstname32_0_, person0_.lastname as lastname32_0_ from Person person0_ where person0_.id=?
select person0_.id as id32_0_, person0_.age as age32_0_, person0_.firstname as firstname32_0_, person0_.lastname as lastname32_0_ from Person person0_ where person0_.id=?
select person0_.id as id32_0_, person0_.age as age32_0_, person0_.firstname as firstname32_0_, person0_.lastname as lastname32_0_ from Person person0_ where person0_.id=?
However this query results in only one query generated, which is what I want:
Code:
List resultList = em.createQuery("select p, count(dogs) from Person p left join p.dogs dogs group by p.id").getResultList();
results in
Code:
select person0_.id as col_0_0_, count(dogs1_.id) as col_1_0_, person0_.id as id10_, person0_.age as age10_, person0_.firstname as firstname10_, person0_.lastname as lastname10_ from Person person0_ left outer join Dog dogs1_ on person0_.id=dogs1_.owner_id group by person0_.id
I would like to be able to use "select new..." constructor in my query though, but why is the generated SQL so inefficient?
I'm using Hibernate 4.1.0.Final, Hibernate JPA2 1.0.1.Final and running against Postgres.