我在代码中收到了以下错误消息,尽管我从未手动调用 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.EntityManager
在close()
、EntityManager.getTransaction().commit( )
以及序列化。
(参见here)。因此,我假设每个 item
在此操作后都会自动分离。对吗?
我怀疑这是我问题的根本原因。我只想显式触发 detach()/merge()
。是否可以更改设置,以便 EntityManager.getTransaction().commit()
不会导致 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/