session - EntityManager.getReference 是否总是在 session 中返回相同的实例?

标签 session object jpa reference entitymanager

我的问题涉及 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);
另见:
  • JSR 317: JavaTM Persistence 2.0
  • 关于session - EntityManager.getReference 是否总是在 session 中返回相同的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11010634/

    相关文章:

    ruby-on-rails-3 - 如何在每条日志消息(Rails 3)中添加 session ID?

    java - 在混合租赁上下文中生成 EntityManager

    hibernate - Tomcat 忽略 persistence.xml

    session - 在 4 个数据中心和 40 台服务器之间共享 "session"信息的最佳方式是什么?

    php - IIS6 : PHP Sessions

    c++ - 有没有更好的方法可以遍历数组中的每个元素而不使用索引的for循环?

    c++ - 什么决定了C++程序中对象销毁的顺序?

    java - 如何为单元测试覆盖 insertable=false

    php - 从不同路径访问 PHP session 变量

    ios - 我如何使这个背景图像在 Collection View 后面静态化