JPA + EclipseLink - 使用封闭的 EntityManager 进行延迟加载

2024-03-19

我在 Java SE 项目中使用 EclipseLink 作为 JPA 提供程序。我已经正确配置了编织以允许延迟加载。

与 Hibernate(抛出 LazyInitializationException)不同,EclipseLink 可以获得 LAZY 关系的代理,即使使用关闭的 EntityManager。为了运行此查询,它从池中获取一个新连接。

是否有某些设置可以禁用或更改此功能的行为?当尝试访问已卸载的属性时,我需要获取 null 值或异常,例如 Hibernate 所做的。

Example:

List<Customer> customers = entityManager.createQuery("from Customer c", Customer.class).getResultList();
entityManager.close(); // Closing the EntityManager

for (Customer customer: customers) {
    customer.getAddress(); // Here EclipseLink executes a query to get the relationship.
}

Thanks.


EclipseLink 允许您访问惰性关系,即使 EntityManager 已关闭。此行为是 EclipseLink 特定的,而不是 JPA 规范的一部分。

当连接关闭时,您将得到您正在寻找的异常。

然而,EclipseLink 将未实例化的列表包装到IndirectList。您可以以编程方式检查列表是否已实例化。

if(customers instanceof IndirectList) {
    boolean foo = ((IndirectList) customers).isInstantiated();
    // ... 
}

也可以看看:

  • https://community.oracle.com/message/1708796 https://community.oracle.com/message/1708796
  • https://eclipse.org/eclipselink/api/2.0/org/eclipse/persistence/indirection/IndirectList.html https://eclipse.org/eclipselink/api/2.0/org/eclipse/persistence/indirection/IndirectList.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JPA + EclipseLink - 使用封闭的 EntityManager 进行延迟加载 的相关文章

随机推荐