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, and 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;
}
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
OneToManyannotation or the sources. From the sources:That being said, while there are very legitimate use cases for
FetchType.EAGER, usingEAGERjust to avoid theLazyInitializationException(which occurs when you try to load a lazy association on a detached object) is more a work around than a real solution.