开发者

JPA: Does EntityManager.find() always return the same object reference for the same key?

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.

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

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

In the setup of my test I've modified the user obj开发者_如何学Cect, 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()));

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.

Thanks!

Java 1.6u22, Toplink Essentials 2.0.1, Spring 2.5.6


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

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.


No it does not. You should rely on object EQUALITY instead of IDENTITY anyway. Override the equals method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜