Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between LEFT JOIN and LEFT JOIN FETCH in Hibernate?

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

Can anyone explain this?

Thanks

like image 419
Barry Avatar asked Jul 27 '11 01:07

Barry


People also ask

What is left join fetch in Hibernate?

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.

Whats the difference between left join and join?

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.

When to use fetch join?

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.


2 Answers

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.

like image 175
Ryan Stewart Avatar answered Oct 07 '22 18:10

Ryan Stewart


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.

like image 23
KeyMaker00 Avatar answered Oct 07 '22 16:10

KeyMaker00