小编典典

带有持久性问题的Java Hibernate问题---如果未定义FetchType,默认方法是什么?

hibernate

大家好,我是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;
}

谢谢!!!!!!!!!


阅读 203

收藏
2020-06-20

共1个答案

小编典典

我想知道如果不声明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(当您尝试在分离的对象上加载懒惰的关联时发生)比真正的解决方案更能解决问题。

2020-06-20