I am trying to understand the difference between LEFT JOIN
and LEFT JOIN FETCH
in Hibernate.
Can anyone explain this?
Thanks
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.
Different Types of SQL JOINs Here are the different types of the JOINs in SQL: (INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table.
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With