Java Hibernate with Persistence Question---if FetchType is not defined, what is the default method?

From the JPA 2.0 spec, the defaults are like so:

  • OneToMany: LAZY
  • ManyToOne: EAGER
  • ManyToMany: LAZY
  • OneToOne: EAGER
  • Columns : EAGER

I am wondering what happens if I don't declare FetchType, does Hibernate determine itself which method to use? Or is it defaulted by EAGER??

Actually, this behavior is not Hibernate specific but defined by the JPA specification and you'd find the answer in the spec or in the javadoc of the OneToMany annotation or the sources. From the sources:

/** (Optional) Whether the association should be
 * lazily loaded or must be eagerly fetched. The
 * {@link FetchType#EAGER EAGER} strategy is a 
 * requirement on the persistenceprovider runtime 
 * that the associatedentities must be eagerly fetched. 
 * The {@link FetchType#LAZY LAZY} strategy is a hint 
 * to the persistence provider runtime.
 */
FetchType fetch() default LAZY;

That being said, while there are very legitimate use cases for FetchType.EAGER, using EAGER just to avoid the LazyInitializationException (which occurs when you try to load a lazy association on a detached object) is more a work around than a real solution.

Tags:

Hibernate

Jpa