Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

hibernate

jpa

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;
}
like image 731
leon Avatar asked Jun 26 '10 23:06

leon


People also ask

What is default FetchType in Hibernate?

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.

What is default FetchType for ManyToOne?

By default, @OneToMany and @ManyToMany associations use the FetchType. LAZY strategy while the @OneToOne and @ManyToOne use the FetchType. EAGER strategy instead.

Is FetchType lazy default?

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.

What is the default fetching strategy in 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.


1 Answers

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

  • OneToMany: LAZY
  • ManyToOne: EAGER
  • ManyToMany: LAZY
  • OneToOne: EAGER
  • Columns : EAGER
like image 154
jmoreira Avatar answered Oct 08 '22 18:10

jmoreira