JPA:EntityManager.find()是否总是为相同的键返回相同的对象引用? [英] JPA: Does EntityManager.find() always return the same object reference for the same key?

查看:170
本文介绍了JPA:EntityManager.find()是否总是为相同的键返回相同的对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对DAO进行了集成测试,其中使用了共享的EntityManager(通过Spring,使用SharedEntityManagerCreator).测试类被标记为@Transactional,被测试的DAO方法也被标记为@Transactional.

I've got an integration test of a DAO in which I use a shared EntityManager (via Spring, using SharedEntityManagerCreator). The test class is marked as @Transactional, as is the DAO method under test.

在测试类和DAO中,我都按如下方式获取用户实体:

In both the test class and the DAO I'm retreiving a User entity as follows:

User user = em.find(User.class, "test");

在测试的设置中,我已经修改了用户对象,但是当测试开始运行时,我没有在DAO中看到修改.事实证明,这两个引用没有引用相同的对象.我在测试课程中使用以下方法证明了这一点:

In the setup of my test I've modified the user object, but I wasn't seeing the modification in the DAO when the test came to run. It turned out that the two references did not refer to the same object; I proved this in my test class using:

System.out.println("User objects equal = " + (user == dao.getUser()));

此打印出来的是假的.我希望每次使用相同键对EntityManager的调用都将返回相同的对象引用,并且很惊讶(有点惊慌!)发现情况并非如此.任何人都可以阐明这一点吗?我已经重构了我的代码,所以实际上这不是问题(无论如何,DAO都不应该在其中包含User对象),但是我仍然想更好地理解这一点.

This printed out false. I would expect that every call to an EntityManager using the same key would return the same object reference, and was surprised (and a bit alarmed!) to find out this was not the case. Can anyone shed any light on this? I've refactored my code so it's not actually an issue (the DAO shouldn't have had the User object in it anyway) but I'd still like to understand this better.

谢谢!

Java 1.6u22,Toplink Essentials 2.0.1,Spring 2.5.6

Java 1.6u22, Toplink Essentials 2.0.1, Spring 2.5.6

推荐答案

find()在持久性上下文范围内返回同一实例.

find() returns the same instance inside a scope of persistence context.

对于共享EntityManager(以JPA Spec术语,由容器管理的事务范围的持久性上下文)而言,持久性上下文的生命周期已绑定到事务,因此,当从同一事务调用时,find()返回相同的实例. 我想在您的案例中,您的测试设置不会与测试方法在同一事务中发生,因此find()会生成不同的实例.

In the case of shared EntityManager (container-managed transaction-scoped persistence context, in JPA Spec terms) lifecycle of persistence context is bound to the transaction, therefore find() returns the same instance when called from the same transaction. I guess in your case setup of your test doesn't happen in the same transaction as a test method, so find() produces different instances.

这篇关于JPA:EntityManager.find()是否总是为相同的键返回相同的对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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