Reputation: 41672
I was wondering in JPQL (not on the entity mappings) how to explicitly fetch an associated field eagerly.
I have ContactAddressLink
(took out the annotations for brevity)
class ContactAddressLink {
Contact contact;
Address address;
... some extra fields ...
}
So I have a query that would go
select cal from Contact c, Address a, ContactAddressLink cal where
cal.contact = c and cal.address = a
Which gives me the query I expected. However, since I would use the addresses after I see a bunch of queries getting the each address.
What I want to do is something like
select cal eager fetch cal.a from Contact c, Address a, ContactAddressLink cal where
cal.contact = c and cal.address = a
I recall seeing something like that, but I can't remember the exact syntax.
Upvotes: 4
Views: 8278
Reputation: 353
Remember as per JPA Specification
all @OneToOne
and @ManyToOne
are fetched eagerly. You should change it to lazy if not, you will fetch those objects always.
Upvotes: 1
Reputation: 90517
Yup. You are right. The syntax is [inner|left] join fetch
. Example :
select cal from ContactAddressLink cal
inner join fetch cal.contact c
inner join fetch cal.address a
where cal.id = 123456789
If you want to match ContactAddressLink
if it has Contact
/Address
, use inner join fetch
.
If you want to match ContactAddressLink
even if it does not have Contact
/Address
, use left join fetch
.
Upvotes: 5