Sleep mode and jpa weirdness; unexpected lazy choice

I am using a rather old version of Hibernate (3.2.4), so it is possible that this is due to this. Unfortunately, the project requirements do not allow me to upgrade.

I have a Foo class with a many-to-one association with Bar. The association is marked with:

lazy="false" fetch="join" 

Now when I do something like:

 em.find(Foo.class, id); 

I get the expected result: one statement connecting the FOO table to the BAR table. However, when I try something like:

 em.createQuery("select f from Foo where f.id = :id") .setParameter("id", id) .getSingleResult(); 

I get one connection, followed by an additional select request to the BAR. The second request seems completely redundant; all the data needed to quickly populate the Foo instance should have been accessible from the original connection. It looks something like this:

 select f.id, f.xyz, ..., b.id, b.xyz, ... from foo f join bar b on b.id = f.bar_id where f.id = ? select b.id, b.xyz, ... from bar b where b.id = ? 

Any thoughts?

+4
source share
1 answer

Hibernate does not respect fetch = "join" when executing HQL queries. From the doc:

The sampling strategy defined in the mapping document affects:

  • search through get () or load ()
  • which happens implicitly when navigating an association.
  • Criteria Requests
  • HQL queries if subquery fetch is used

In the case of HQL queries, you should use left join fetch :

 em.createQuery("select f from Foo f left join fetch f.bar where f.id = :id") .setParameter("id", id) .getSingleResult(); 
+2
source

All Articles