Saturday, March 17, 2012

JPA find() vs. getReference()

How are persistent entities in JPA retrieved?
Here are 2 possibilities besides other query calls:

  • find()
  • getReference()
How are they used?
- Find() is called on the EntityManager and the method needs 2 parameters:
  1. Type of the wanted entity
  2. Identity: Id of the wanted entity
Caller gets the retrieved entity or null.
Example:
EntityManagerFactory ef = Persistence.createEntityManagerFactory("myapp") ;
EntityManager em =  ef.createEntityManager();
....
Client k = em.find(Client.class, 70992);


- GetReference() is used similarly.
Client k = em.getReference(Client.class, 70922);
If the entity for the stated id is not known in the persistence context, an EntityNotFoundException() is thrown.

What is the difference between both methods?
Find() delivers the entity from the cache of the persistence context or if he is not there, it will be loaded from the database.
GetReference() does not load the entity immediately. A proxy( a certain object, a so called "deputy" with enriched methods for loading the actual entity) is returned. So it is a realisation with help of LazyLoading.
Only if the attributes of the proxy or other persistence methods are needed/called the proxy interacts and loads the actual entity from the database.

When should one use which method?
The usage of find() should take priority over query methods, because find() can return already loaded entities from the cache of the persistence context.
If you do know, that an entity is need later on, the usage of getReference() is a good choice.

No comments:

Post a Comment