问题
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 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()));
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
回答1:
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.
回答2:
No it does not. You should rely on object EQUALITY instead of IDENTITY anyway. Override the equals method.
来源:https://stackoverflow.com/questions/4226772/jpa-does-entitymanager-find-always-return-the-same-object-reference-for-the-s