Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
MercurieVV Avatar asked Nov 23 '16 10:11

MercurieVV


People also ask

What fetch strategies do you know what is the default?

By default, the JPA @ManyToOne and @OneToOne annotations are fetched EAGERly, while the @OneToMany and @ManyToMany relationships are considered LAZY. This is the default strategy, and Hibernate doesn't magically optimize your object retrieval, it only does what is instructed to do.

What is the default FetchType?

Okay, so we talked about the fact that FetchType. LAZY is the default fetch type for all Hibernate annotation relationships. We also talked about the fact that when you use the Lazy fetch type, Hibernate won't load the relationships for that particular object instance.

What is the default fetch mode for one to many association in Hibernate JPA?

EAGER . By default, @OneToMany and @ManyToMany associations use the FetchType. LAZY strategy while the @OneToOne and @ManyToOne use the FetchType. EAGER strategy instead.

Is FetchType lazy default?

By default, Fetch type would be Lazy. FetchType. LAZY: It fetches the child entities lazily, that is, at the time of fetching parent entity it just fetches proxy (created by cglib or any other utility) of the child entities and when you access any property of child entity then it is actually fetched by hibernate.


2 Answers

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.

like image 110
Chaouki Dhib Avatar answered Oct 12 '22 15:10

Chaouki Dhib


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.

like image 28
Dherik Avatar answered Oct 12 '22 14:10

Dherik