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;
}
FetchType, on the other hand, defines whether Hibernate will load data eagerly or lazily. The exact rules between these two are as follows: if the code doesn't set FetchMode, the default one is JOIN and FetchType works as defined. with FetchMode.
By default, @OneToMany and @ManyToMany associations use the FetchType. LAZY strategy while the @OneToOne and @ManyToOne use the FetchType. EAGER strategy instead.
By default, Fetch type would be Lazy. FetchType. LAZY: It fetches the child entities lazily, that is, at the time of fetching parent entity it just fetches proxy (created by cglib or any other utility) of the child entities and when you access any property of child entity then it is actually fetched by hibernate.
By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.
From the JPA 2.0 spec, the defaults are like so:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With