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



Question:

Hi guys I am new to Hibernate and JPA

I wrote some functions, initially, I set fetch = FetchType.LAZY in the entity class. But it gave me error: "org.hibernate.LazyInitializationException: could not initialize proxy - no Session"

@OneToMany(cascade = CascadeType.ALL, mappedBy = "logins", fetch=FetchType.LAZY,targetEntity=Invoice.class)  public List<Invoice> getInvoiceList() {      return invoiceList;  }    public void setInvoiceList(List<Invoice> invoiceList) {      this.invoiceList = invoiceList;  }  

Then I changed it to fetch = FetchType.EAGER, it worked fine..... I am wondering what happen if I don't declare FetchType, does Hibernate determine itself which method to use? Or is it defaulted by EAGER??

@OneToMany(cascade = CascadeType.ALL, mappedBy = "logins", fetch=FetchType.EAGER,targetEntity=Invoice.class)  public List<Invoice> getInvoiceList() {      return invoiceList;  }    public void setInvoiceList(List<Invoice> invoiceList) {      this.invoiceList = invoiceList;  }  

THANKS!!!!!!!!!


Solution:1

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.


Solution:2

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

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »