Reputation: 20210
In both OneToMany is lazy thank god.
Is there a setting in hibernate to override this very bad setting? There is way too many people who keep adding ManyToOnes without setting them to lazy(ie. they forget to add FetchType.LAZY) resulting in tons of unecessary joins and in some cases resulting in 6 tables being joined which was not needed.
Everything should really be lazy unless the developer moves to JQL to eagerly fetch something. It then is more consistent and aids the developers from not making these mistakes every time they add a ManyToOne annotation
OR, in hibernate 5.2, can one still use hibernate annotations instead? but then I need to somehow get rid of JPA annotations off the classpath as I am afraid they accidentally come back to us(us all being human and all).
I found this great article which explains it better than I could have on how everything should be lazy as well https://vladmihalcea.com/eager-fetching-is-a-code-smell/
thanks, Dean
Upvotes: 2
Views: 378
Reputation: 9022
It is not possible for Hibernate (or any other framework) to distinguish the default of an annotation attribute from the same value that was set.
I mean at runtime @ManyToOne
and @ManyToOne(fetch = FetchType.EAGER)
are exactly the same.
But as you can't change the runtime behavior, you could at least tweak the compile time: You could add a Checkstyle rule (or anything similar) that enforces your coworkers to always set the fetch type explicitly.
Example for Checkstyle:
<module name="RegexpSinglelineJava">
<property name="format" value="@(One|Many)ToOne(?!\([^)]*fetch)"/>
<property name="message" value="Please declare the fetch type (and use EAGER sparingly)"/>
<property name="ignoreComments" value="true"/>
</module>
That would add a compile time warning, if the fetch was not defined after a @OneToOne
or @ManyToOne
.
Upvotes: 3
Reputation: 390
There's no way to override the default globally, but you can try get the source code, change it, and compile it.
https://github.com/eclipse/javax.persistence/blob/master/src/javax/persistence/ManyToOne.java
Line 111.
FetchType fetch() default EAGER;
Upvotes: 1