gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:13:31 25 4
gpt4 key购买 nike

我在代码中收到了以下错误消息,尽管我从未手动调用 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'spersistence 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'spersistence context.

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com