Video in progress
How does JOIN FETCH in JPQL differ from a plain JOIN?
A plain JOIN only adds the table for filtering or a condition and does not load the related entities. JOIN FETCH reads the related objects in the same query and fills them into the entity.
📖 Answer
// filter only: items stay lazy, and opening them later means another SELECT
select o from Order o join o.items i where i.price > 100
// items are loaded together with the order
select o from Order o join fetch o.items where o.status = 'NEW'
After the second query, order.getItems() doesn't hit the database: the data is already there.
Details you should know:
- if you fetch join a collection, the order rows are duplicated in the SQL result (one per item). Hibernate 6 removes duplicates from entity results by itself; in Hibernate 5 you had to write
distinct; - if you combine a
join fetched collection withsetMaxResults(pagination), Hibernate applies the limit in memory and logs a warning. On a big table that is dangerous; inner join fetchdrops parents that have no child rows. If you need all of them, useleft join fetch.
Sign up to mark studied questions and save your progress.