Difference between LEFT JOIN and LEFT JOIN FETCH in Hibernate?
Asked Answered
S

2

76

I am trying to understand the difference between LEFT JOIN and LEFT JOIN FETCH in Hibernate.

Can anyone explain this?

Thanks

Stroll answered 27/7, 2011 at 1:41 Comment(0)
B
92

The "fetch" tells hibernate to load it now instead of letting it be loaded lazily. The reference guide has a whole chapter dealing with such things that it's good to be acquainted with.

Barbrabarbuda answered 27/7, 2011 at 1:46 Comment(0)
C
22

You can use FETCH to tune your application performance. It is one of the orthogonal notions of Hibernate, which answer to the question how (fetch style) the association is fetched. There are 4 styles: select / subselect / batch / join.

The second notion is when (fetch timing) it should be fetched. You can configure it with the one of the 6 properties defined by Hibernate, where the most 4 properties are: eager, lazy, extra lazy, proxy.(hibernate-core)

Hibernate use by default:

  • collection: lazy select fetching
  • singe-valued assocation: lazy proxy fetching

Join

JOIN or (LEFT JOIN) will only return the parent objects.

Join fetch

JOIN FETCH (or LEFT JOIN FETCH) will collect all the associations along with their owner object. Meaning that the collection will be retrieved in the same select. This can be shown by enabling Hibernate's statistics.

A (left/outer) join fetch is great for *ToOne (many-to-one or one-to-one) associations. It is used with non-bags but be aware of the cartesian problem that might occur, when the tables' cardinality is high. Note that a select fetch style is in most of the cases faster.

Note that less select statements is synonym to less round-trips between hibernate and the database, but it not synonym to a better performance.

Chough answered 13/12, 2018 at 10:13 Comment(2)
Good read, additional read from Vlad: https://mcmap.net/q/81059/-what-is-the-difference-between-join-and-join-fetch-when-using-jpa-and-hibernateTachymetry
When you say "along with their owner object", is the "owner object" the originally queried item, or the one from the joined table?Pappas

© 2022 - 2024 — McMap. All rights reserved.