Java Hibernate with Persistence问题---如果没有定义FetchType,默认方法是什么?

时间:2010-06-26 23:41:11

标签: hibernate jpa

大家好我是Hibernate和JPA的新手

我写了一些函数,最初,我在实体类中设置了 fetch = FetchType.LAZY 。 但它给了我错误: “org.hibernate.LazyInitializationException:无法初始化代理 - 没有会话”

@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;
}

然后我将其更改为fetch = FetchType.EAGER,它工作得很好..... 我想知道如果我不声明FetchType会发生什么,Hibernate是否确定自己使用哪种方法?或者它是否被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;
}

感谢!!!!!!!!!

2 个答案:

答案 0 :(得分:68)

从JPA 2.0规范中,默认值如下:

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

答案 1 :(得分:6)

  

我想知道如果我不声明FetchType会发生什么,Hibernate会确定自己使用哪种方法吗?或者它是否被EAGER默认?

实际上,这种行为不是特定于Hibernate的,而是由JPA规范定义的,您可以在OneToMany注释的规范或javadoc或源中找到答案。来自消息来源:

/** (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;

话虽如此,虽然FetchType.EAGER有非常合法的用例,但使用EAGER只是为了避免LazyInitializationException(当您尝试在分离时加载惰性关联时会发生这种情况)对象)更像是一种解决方案而不是真正的解决方案。