What is the difference between EntityManager.find() and EntityManger.getReference()?

user237673 picture user237673 · Mar 30, 2011 · Viewed 49.1k times · Source

Whats is the difference between

<T> T EntityManager.find(Class<T> entityClass, Object primaryKey) and 
<T> T EntityManager.getReference(Class<T> entityClass, Object primaryKey) 

?

I think getReference returns entity if it is managed. and find returns entity if it is managed else executes SQL on database to make it managed.

Please confirm.


Context: From webapp I get primary key of object to be deleted (pk of type long); to entity should be managed to delete.

EntityManager.remove(Object entity)

to pass managed entity to entitymanager remove method 'whats the better and correct option? find or getReference?'

Answer

Daniel picture Daniel · Mar 30, 2011

JPA has the concept of an EntityManager, as you know. During your work in the entity manager some objects are loaded from the database, can be modified and afterwards flushed to the database.

find() has to return an initialized instance of your object. If it is not already loaded in the EntityManager, it is retrieved from the database.

getReference() is allowed to return a proxy instead of an initialized instance, if the entity has not been loaded in the EntityManager before. In this proxy, only the primary key attribute is initialized. Proxies can be created without hitting the database, because the only initialized attribute is already given to the getReference() function.

The latter is useful when you have an entity A referencing an entity B, and you want to set the b-attribute of A to B, without having to load B from the database.

Only if you reference other attributes of B, the proxy will be initialized.