Hibernate:commit()后分离实体
Hibernate: detached of entities after commit()
尽管我从未手动调用 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.
尽管我从未手动调用 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.