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?
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.
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.
EAGER . By default, @OneToMany and @ManyToMany associations use the FetchType. LAZY strategy while the @OneToOne and @ManyToOne use the FetchType. EAGER strategy instead.
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.
If the Hibernate annotation @Fetch is not present on a field, then the default FetchMode for this field is:
My source for this information is the code itself (Hibernate 5.0): HERE, HERE and most importantly, HERE.
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.
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