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);
-- Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there.

- 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.

--Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.


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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值