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

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

问题描述

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

?

我认为 getReference 返回实体,如果它被管理.find 返回实体,如果它是托管的,否则在数据库上执行 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);实体应该被管理删除.

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 删除方法'什么是更好和正确的选项?查找或获取参考?'

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天全站免登陆