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

I have a DAO integration test in which I use the generic EntityManager (via Spring, using the SharedEntityManagerCreator). The testing class is marked as @Transactional, as is the DAO test method.

In both the test class and the DAO, I return the User object as follows:

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

In setting up my test, I changed the user object, but I did not see the change in the DAO when the test came into effect. It turned out that these two links do not apply to the same object; I proved this in my test class using:

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

This is printed incorrectly. I would expect that each call to EntityManager using the same key will return the same object reference and was surprised (and a little alarmed!) To find out that it is not. Can anyone shed some light on this? I reworked my code, so this is actually not a problem (the DAO should not have a User object in it), but I still would like to understand it better.

Thank!

Java 1.6u22, Toplink Essentials 2.0.1, Spring 2.5.6

+3
source share
2 answers

find()returns the same instance inside the persistence context area .

EntityManager ( , , JPA Spec) persistence , find() , , , , find() .

+5

, . EQUALITY, IDENTITY. equals.

0

Source: https://habr.com/ru/post/1775867/


All Articles