views:

385

answers:

1

The following query is supposed to return about 800 objects. The problem is that hibernate actually executes 800 queries to get them all. It appears to execute one query to get the ids and then executes one query for every object to get the specific data about the object. It takes over 60 seconds for this query to return.

List<AUser> result = em.createQuery("FROM AUser where company=:companyId")
.setParameter("companyId",company.getId())
.getResultList();

The native query is much faster.

List<AUser> result = em.createNativeQuery("select a.* FROM AUser a where a.company=:companyId")
.setParameter("companyId",company.getId())
.getResultList();

The above query takes less than one second to return.

Why the difference?

+2  A: 

The original issue is caused by property(ies) of AUser being eagerly fetched (confirmed by HappyEngineer in comment).

Answering the follow-up question:

Generally, the best approach is to map associations as lazy:

@ManyToOne(fetch = FetchType.LAZY)
private Company company;

You can then override fetch mode within your query by using join fetch:

select user
  from AUser user left join fetch user.company
 where user.company.id = :companyId

See Associations and Joins chapter in Hibernate documentation for more details.

ChssPly76
I'm using JPA, so the syntact is a bit different. I had to use "LEFT OUTER JOIN" rather than "left join fetch". It all works now though.
HappyEngineer
Your question is tagged as "hibernate" and "hql", though. You may be using JPA **annotations** and `EntityManager` but HQL remains HQL. `LEFT OUTER JOIN` is equivalent to `LEFT JOIN`, it's the `FETCH` part that's important.
ChssPly76