MercurieVV
MercurieVV

Reputation: 404

How hibernate decide which of FetchMode use by default?

In our project we use Hibernate, and in logs we observe that it sometimes use Join and sometimes Select for relations (as I understand it's FetchMode) when we didnt specify FetchMode.

How do Hibernate decide which one of FetchMode use if no specified?

Is there any specification for this? Any lines of code? Any Article?

Upvotes: 7

Views: 8702

Answers (3)

Eugene Khyst
Eugene Khyst

Reputation: 10315

If a field is not annotated with @Fetch, then the default FetchMode for this field depends on a FetchType and how the query is done:

  • FetchType.LAZY => FetchMode.SELECT
  • FetchType.EAGER:
    • getting by ID (Session.get) => FetchMode.JOIN
    • JPQL query => FetchMode.SELECT
    • Criteria API query => FetchMode.SELECT

Upvotes: 4

Dherik
Dherik

Reputation: 19120

Looking the generated SQL when no FetchMode is specified and the FetchType is EAGER, the default is JOIN in Hibernate.

Sadly, I can't find this information in the official docs.

About the use of SELECT even when JOIN is default, I supposed that are some queries that can't be resolved in a one single query, like this:

But if you allow B without C, Hibernate just HAS TO check presence of C at the moment it loads B. But a SELECT to check presence is just inefficient because the same SELECT may not just check presence, but load entire object. So lazy loading goes away.

Upvotes: 1

Chaouki Dhib
Chaouki Dhib

Reputation: 429

If the Hibernate annotation @Fetch is not present on a field, then the default FetchMode for this field is:

  • if this field has FetchType = EAGER, then FetchMode = JOIN.
  • Otherwise, FetchMode = SELECT.

My source for this information is the code itself (Hibernate 5.0): HERE, HERE and most importantly, HERE.

Upvotes: 17

Related Questions