JPA EntityManager.detach() 仍然加载惰性关系

JPA EntityManager.detach() still load lazy relations

我遇到了一个与我对它应该如何工作的理解不符的问题。我有一个 Arquillian 测试,它使用 JPA 查询测试存储库方法。

测试持久化一个对象,然后用字段中的第一个持久化对象持久化另一个对象。然后它调用存储库方法。接下来测试分离(并清除实体管理器,检查对象是否不包含在 em 等中)。最后测试检查相关对象是否存在(它不应该因为查询不应该读取关系)。

正如预期的那样,在调试器中查看时,相关对象为空,但是当断言实际使用 getRelatedObject 方法时,加载相关对象。

伪代码澄清(我希望):

FirstObject f = new FirstObject();
em.persist(f);
SecondObject s = new SecondObject();
s.setFirstObject(f);
em.persist(f);
MyRepo r = new MyRepo();
SecondObject result = r.runQuery(f.getId());
em.detach(result); //result.getFirstObject is null
em.clear();
assertIsNull(result.getFirstObject()); //loads first object and test fails

难道我的理解有误,相关对象还应该加载吗?我期待一个 LazyInit 异常。

如果我的理解是错误的,如何验证查询没有填充相关对象我不会不会?

(是的,使用 dto-objects 而不是实体更好,我知道......我们已经进行了讨论,但我被否决了)

本书 Pro JPA 2(Apress,p160)注释

"The behavior of accessing an unloaded attribute when the entity is detached is not defined. Some vendors might attempt to resolve the relationship, while others might simply throw an exception or leave the attribute uninitialized."

我个人没有使用 EclipseLink 的经验,可以在该区域的文档中找到任何明确的内容,但是以下链接都表明 EclipseLink 将在您访问分离集合上的惰性关联时尝试解析关系。

Eclipselink Lazy Loading

http://issues.apache.org/jira/browse/OPENJPA-2483

http://blog.ringerc.id.au/2012/06/jpa2-is-very-inflexible-with-eagerlazy.html