我的问题涉及 EntityManager.getReference。鉴于我在一个 JPA session 中,我能否确定对于同一实体和同一主键的 EntityManager.getReference 两次调用,我总是获得相同的 java 对象实例?
对于两个不同的 session ,我怀疑会获得两个不同的 java 对象实例 - 真的是这样吗?
我很想知道一般规则,而不是任何具体的实现是如何工作的。它是否由规范定义? (我自己无法找到它)。
Person p1 = EntityManager.getReference(Person.class, 1L);
Person p2 = EntityManager.getReference(Person.class, 1L);
if (p1 == p2) {
System.out.println("SAME");
} else {
System.out.println("DIFF");
}
最佳答案
是的,这是 JPA 的基本保证 - 在持久化上下文(即 session , EntityManager
)的范围内,托管实体的对象标识与其数据库标识匹配:
7.1 Persistence Contexts
A persistence context is a set of managed entity instances in which for any persistent entity identity there is a unique entity instance.
和
getReference()
返回一个托管实例:3.2.8 Managed Instances
...
The contains() method can be used to determine whether an entity instance is managed in the current persistence context.
The contains method returns true:
- If the entity has been retrieved from the database or has been returned by getReference, and has not been removed or detached.
- If the entity instance is new, and the persist method has been called on the entity or the persist operation has been cascaded to it.
此外,这种保证意味着在持久化上下文的范围内,无论您如何获得相同的 id,您都将获得相同的实体实例(通过
find()
、 getReference()
、 merge()
、查询或关系遍历) .例如,如果您从
getReference()
获得代理与该实体的所有进一步工作都将通过该代理进行:Person p1 = EntityManager.getReference(Person.class, 1L);
Person p2 = EntityManager.find(Person.class, 1L);
assertSame(p1, p2);
另见:关于session - EntityManager.getReference 是否总是在 session 中返回相同的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11010634/