2
  • old school hibernate - ManyToOne was lazy
  • JPA - ManyToOne is eager

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

2 Answers 2

3

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.

1

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;
1
  • At least for a JEE application server (which contains other applications) this is something you can't do. So I would be cautious with the word always here. Oct 9, 2016 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.