java - 即使数据库中包含实体,为什么 'EntityManager.contains(..)' 也会返回 false?

标签 java jpa entitymanager jpa-2.1

我用过这个JPA: check whether an entity object has been persisted or not 要知道我是否坚持或合并我的实体,它将如下所示:

if (!getEntityManager().contains(entity)) {
        System.out.println(" PERSIST ");            
    } else {
        System.out.println(" MERGE ");
    }

情况是 - 即使我编辑我的实体 - 它也不会被识别为合并。

这怎么可能以及如何让它发挥作用?

最佳答案

根据JPA 2.1 specification (PDF第72页),

EntityManager方法public boolean contains(Object entity)是:

Check if the instance is a managed entity instance belonging to the current persistence context.

因此,检查不是针对实际数据库进行的,而是针对当前 persistence context 进行的。

此外,在规范文档的 PDF 第 86 页上,我们发现:

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.

The contains method returns false:

• If the instance is detached.

很可能,在执行代码片段的调用代码时,您处于分离实体状态。因此,呼吁 contains(..)始终评估为 false .

作为替代方案,您可以使用

  • public <T> T find(Class<T> entityClass, Object primaryKey) (参见第 66 页)
  • public <T> T getReference(Class<T> entityClass, Object primaryKey) (见第68页)

检查底层数据库中是否存在元组。您选择上述哪一种方法将取决于您的代码/应用程序的上下文。

希望有帮助。

关于java - 即使数据库中包含实体,为什么 'EntityManager.contains(..)' 也会返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49113545/

相关文章:

java - 静态元模型主键属性未填充(NullPointerException)

jpa - 如何在 EntityManager (JPA) 中查找所有托管附加对象

c++ - 碰撞不一致

java - CDI 交易警告

java - 如何打印增强型 for 循环的前 10 行

java - JPA 中的映射键 : Primary key is a foreign key

java - CDI 使用 @Produces 按字段名称注入(inject) EntityManager

java - ANTLR v4、JavaLexer 和 JavaParser 返回 null 作为解析树

java - 对 iPhone 和 Java 应用程序的可嵌入脚本语言的建议?

oracle - JPA 2.0 Oracle DATE 时间为空