Reputation: 2233
I'm using a rather old version of Hibernate (3.2.4) so it's possible this is related to that. Unfortunately the project requirements prevent me from upgrading.
I have a class Foo with many-to-one association to Bar. The association is flagged:
lazy="false" fetch="join"
Now when I do something like:
em.find(Foo.class, id);
I get the expected result: a single statement joining the FOO table with 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 the single join followed by an additional select query against BAR. The second query seems to be entirely superfluous; all the data needed to eagerly populate an instance of Foo should have been available from the initial join. It looks roughly 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?
Upvotes: 4
Views: 513
Reputation: 242686
Hibernate doesn't respect fetch = "join"
when executing HQL queries. From the documentation:
The fetch strategy defined in the mapping document affects:
- retrieval via get() or load()
- retrieval that happens implicitly when an association is navigated
- Criteria queries
- HQL queries if subselect fetching is used
In the case of HQL queries you have to use left join fetch
:
em.createQuery("select f from Foo f left join fetch f.bar where f.id = :id")
.setParameter("id", id)
.getSingleResult();
Upvotes: 2