开发者

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

开发者 https://www.devze.com 2023-02-20 21:35 出处:网络
Whats is the difference between <T> T EntityManager.find(Class<T> entityClass, Object primaryKey) and

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 ma开发者_如何学JAVAke 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?'


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.


The book Beginning Java EE 6 Platform with GlassFish 3, mention the differences in page 135: "Finding By ID"

find() if the entity is found, it is returned; if it is not found, a null value is returned.

MyEntity obj = em.find(MyEntity.class, id);
if(obj != null){
   // Process the object 
}

getReference() is intended for situations where a managed entity instance is needed, but no data, other than potentially the entity's primary key, being accessed.

try {
    MyEntity obj = em.getReference(MyEntity.class, id);
    // Process the object
} catch (EntityNotFoundException e) {
    // Entity Not Found
}


getReference() does not retrieve the full object but only a proxy and therefore can be more efficient if you do not access the members of the object.

For instance when creating a new object to insert into your database, it might have to refer to another object which already has been stored in the database.

For JPA to store the new object correctly only the primary key of the referred object is needed. By using getReference() you get a proxy which contains the primary key and you save the cost of loading the complete object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号