简体   繁体   中英

How to perform an EAGER fetch in JPQL

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM