本文介绍了JPA + EclipseLink-使用封闭的EntityManager进行延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using EclipseLink as JPA provider in a Java SE project. I have properly configured the weaving to allow the Lazy Loading.

与Hibernate(引发LazyInitializationException)不同,EclipseLink甚至可以在关闭EntityManager的情况下获取LAZY关系的代理.要运行此查询,它将从池中获取一个新的连接.

Unlike Hibernate (which throws LazyInitializationException), EclipseLink can get a proxy of LAZY relationship, even with a closed EntityManager. To run this query, it gets a new connection from the pool.

是否存在一些禁用或更改此功能行为的设置?尝试访问未加载的属性时(例如Hibernate这样做),我需要获取一个null值或一个异常.

Is there some setting that disables or changes the behavior of this feature? I need to get a null value or an exception when trying to access an unloaded attribute, such as Hibernate does.

示例:

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 allows you to access lazy relations, even when the EntityManager has been closed. This behaviour is EclipseLink-specific and not part of the JPA spec.

关闭连接后,您将获得所需的异常.

You will get the Exception you are looking for, when the Connection has been closed.

但是,EclipseLink将未实例化的列表包装到IndirectList中.您可以通过编程方式检查列表是否已实例化.

However, EclipseLink is wrapping not-instantiated Lists into IndirectList. You are able to check programmatically if the List has been instantiated or not.

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

另请参阅:

  • https://community.oracle.com/message/1708796
  • https://eclipse.org/eclipselink/api/2.0/org/eclipse/persistence/indirection/IndirectList.html

这篇关于JPA + EclipseLink-使用封闭的EntityManager进行延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 01:34