Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...