java - Hibernate:提交()后分离实体

标签 java hibernate detach

我在代码中收到了以下错误消息,尽管我从未手动调用 detach() 命令:

org.hibernate.PersistentObjectException: detached entity passed to persist: my.entity

我的实体使用持久化

try
        {
                entityManager.getTransaction().begin(); 
                entityManager.persist(item);
                entityManager.getTransaction().commit(); 
        }
        catch(final Exception e)
        {
               entityManager.getTransaction().rollback();
               LOGGER.err("Error at persist.");
               throw new Exception();
        }

在文献中,我发现javax.persistence.EntityManagerclose()EntityManager.getTransaction().commit( ) 以及序列化。 (参见here)。因此,我假设每个 item 在此操作后都会自动分离。对吗?

我怀疑这是我问题的根本原因。我只想显式触发 detach()/merge() 。是否可以更改设置,以便 EntityManager.getTransaction().commit() 不会导致 detach()

最佳答案

实体只有在关闭或清除事务时才会分离,而不是在提交时分离?! ..

Detach

The following operations clear the entire EntityManager's persistence context and detach all managed entity objects:

*Invocation of the close method, which closes an EntityManager.

*Invocation of the clear method, which clears an EntityManager's persistence context.

*Rolling back a transaction - either by invocation of rollback or by a commit failure.

关于java - Hibernate:提交()后分离实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40761350/

相关文章:

java - 我的上一个 ImageView 图像按钮不起作用

java - 来自 Firebird 数据库的 Netbeans Hibernate 映射文件和 POJO 向导中的 NullPointerException

Python pthread_detach 模拟

java - 无法关闭前一帧以查看新帧 java

java - 回收商 View 内容器的多重选择

java - 如何在Java中将一个模拟对象注入(inject)另一个模拟对象的模拟中?

java - 为什么在部署到 tomcat 7 后我的 .war 不启动,但运行嵌入式服务器工作正常?

mysql - 为辅助表生成的主键在 @OneToMany 关系上为空

c - 如何从共享内存中分离字符串数组? C

c++ - 分离线程然后让它超出范围(并使其仍在运行)是否安全?