JPA EntityManager.detach()仍然加载惰性关系 [英] JPA EntityManager.detach() still load lazy relations

查看:1166
本文介绍了JPA EntityManager.detach()仍然加载惰性关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,这与我对它应该如何工作的理解背道而驰.我有一个Arquillian-test,它使用JPA查询来测试存储库方法.

I got a problem that goes against my understanding of how it supposed to work. I have a Arquillian-test that tests a repository-method with a JPA query.

测试将持久化一个对象,然后将另一个对象与字段中的第一个持久化对象持久化.然后,它调用存储库方法.接下来,测试分离(并清除entitymanager,检查对象是否包含在em中,等等).最后,测试检查相关对象是否存在(因为该查询不应该读取该关系,所以不应该这样做).

The test persists an object, and then persists an another object with the first persisted object in a field. Then it calls the repository-method. Next the test detaches (and clear the entitymanager, checks that the object is not contained in the em etc etc). Last the test checks if the related object is there or not (it shouldn't since the query is not supposed to read the relation).

按预期,在调试器中查找时,相关对象为null,但是当断言实际使用getRelatedObject方法时,将加载相关对象.

As expected, when looking in the debugger, the related object is null, but when the assert actually uses the getRelatedObject-method, is loads the related object.

要澄清的伪代码(我希望如此):

Pseudocode to clarify (i hope):

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例外.

Is it my understanding that is wrong, should the related object still load? I expected a LazyInit-exception.

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

If i'm my understanding is wrong, how to verify that a query doesn't populate related object I don't won't?

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

(yes, using dto-objects instead of the entity is better, I know... we have had that discussion and I was overruled)

推荐答案

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

The book Pro JPA 2 (Apress, p160) notes

当实体为 未定义分离. 某些供应商可能会尝试解决 关系,而其他人可能只是抛出异常或离开 该属性未初始化."

"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在您访问独立集合上的惰性关联时将尝试解决这种关系.

I do not have experience of EclipseLink personally and can find anything definitive in the documentation in this area however the following links all suggest that EclipseLink will try and resolve the relationship when you access a lazy association on a detached collection.

Eclipselink延迟加载

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

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

这篇关于JPA EntityManager.detach()仍然加载惰性关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆