Yes, this is a basic JPA guarantee - in the context of the persistence context (i.e., session, EntityManager
), the identifier of the managed object object corresponds to their database identifier:
7.1 Storage contours
A persistence context is a collection of managed entity instances in which a unique entity instance exists for any persistent entity identifier.
and getReference()
returns a managed instance:
3.2.8 Managed Instances
...
The contains () method can be used to determine whether an instance of an object is managed in the current persistence context.
The contains method returns true:
- If the object was retrieved from the database or was returned by the getReference function and has not been deleted or deleted.
- If the object instance is new and the persist method was called in the entity, or the persist operation was cascaded on it.
In addition, this guarantee means that inside the persistence context area, you will receive the same instance of the object for the same identifier, regardless of how you received it (via find()
, getReference()
, merge()
, query, or crawl relationship )
For example, if you received a proxy from getReference()
, all further work with this entity will happen through this proxy:
Person p1 = EntityManager.getReference(Person.class, 1L); Person p2 = EntityManager.find(Person.class, 1L); assertSame(p1, p2);
See also:
source share