Does EntityManager.getReference always return the same instance inside a session?

My question is about EntityManager.getReference. Given that I am in the same JPA session, can I be sure that for two calls to EntityManager.getReference for the same object and the same primary key, I always get the same java object instance? For two different sessions, I suspect I'm getting two different instances of Java objects - is this really so?

I am interested in knowing a general rule, and not how any particular implementation works. Is this defined by the specification or not? (I could not figure it out myself).

Person p1 = EntityManager.getReference(Person.class, 1L); Person p2 = EntityManager.getReference(Person.class, 1L); if (p1 == p2) { System.out.println("SAME"); } else { System.out.println("DIFF"); } 
+4
source share
1 answer

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:

+2
source

All Articles