EntityManager.find()和EntityManger.getReference()之间有什么区别? [英] What is the difference between EntityManager.find() and EntityManger.getReference()?

查看:129
本文介绍了EntityManager.find()和EntityManger.getReference()之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么区别

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

我认为如果管理,getReference会返回实体。
并找到返回实体,如果它是托管的,则在数据库上执行SQL以使其受管理。

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.

请确认。

上下文:
从webapp我得到要删除的对象的主键(pk类型为long);应该管理实体到删除。

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)

将托管实体传递给entitymanager删除方法'什么是更好更正确的选项? find或getReference?'

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

推荐答案

正如您所知,JPA具有EntityManager的概念。在您在实体管理器中工作期间,一些对象从数据库加载,可以修改,然后刷新到数据库。

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()必须返回对象的初始化实例。如果它尚未在EntityManager中加载,则从数据库中检索它。

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()是允许的如果实体尚未在EntityManager中加载,则返回代理而不是初始化实例。在此代理中,仅初始化主键属性。 可以创建代理而无需访问数据库,因为已经为getReference()函数提供了唯一的初始化属性。

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.

后者很有用当你有一个实体A引用一个实体B,你想要将A的b属性设置为B,而不必从数据库中加载B.

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.

如果你引用B的其他属性,代理将被初始化。

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

这篇关于EntityManager.find()和EntityManger.getReference()之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆