我在 Java SE 项目中使用 EclipseLink 作为 JPA 提供程序。我已正确配置编织以允许延迟加载。
与 Hibernate(抛出 LazyInitializationException)不同,EclipseLink 可以获得 LAZY 关系的代理,即使使用关闭的 EntityManager 也是如此。为了运行此查询,它从池中获取一个新连接。
是否有某些设置可以禁用或更改此功能的行为?当尝试访问已卸载的属性时,我需要获取 null 值或异常,例如 Hibernate 所做的那样。
示例:
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.
}
谢谢。
最佳答案
EclipseLink 允许您访问惰性关系,即使 EntityManager 已关闭。此行为是 EclipseLink 特定的,而不是 JPA 规范的一部分。
当连接关闭时,您将得到您正在寻找的异常。
但是,EclipseLink 将未实例化的列表包装到 IndirectList
中。您可以以编程方式检查列表是否已实例化。
if(customers instanceof IndirectList) {
boolean foo = ((IndirectList) customers).isInstantiated();
// ...
}
另请参阅:
关于java - JPA + EclipseLink - 使用封闭的 EntityManager 进行延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32694355/