简体   繁体   English

休眠:commit()之后脱离实体

[英]Hibernate: detached of entities after commit()

I have recived the following error message in my code, althrough I never manually call the detach() command: 我从未在代码中收到以下错误消息,因为我从未手动调用detach()命令:

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

My entities are persited using 我的实体使用

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();
        }

In the literature I found the hint that the javax.persistence.EntityManager automatically detached entities on close() , EntityManager.getTransaction().commit() and on serialisation. 在文献中,我发现了javax.persistence.EntityManagerclose()EntityManager.getTransaction().commit()和序列化时自动分离实体的提示。 (see here ). (请参阅此处 )。 So I assume that every item is automitically detached after this operation. 因此,我假设此操作后,每个item都会自动分离。 Correct? 正确?

I suspect that this is the root cause of my issues. 我怀疑这是我问题的根本原因。 I want to trigger the detach() / merge() only explicitly. 我只想明确触发detach() / merge() Is there a posiblity to change the settings, so that EntityManager.getTransaction().commit() does NOT cause an detach() ? 是否有可能更改设置,以便EntityManager.getTransaction().commit()不会导致detach()

Entities get detached only when you close or clear the transaction not when you commit ?! 实体仅在您关闭或清除事务时才分离,而在提交时则不分离? .. ..

Detach 分离

The following operations clear the entire EntityManager's persistence context and detach all managed entity objects: 以下操作清除了整个EntityManager的持久性上下文并分离了所有托管实体对象:

*Invocation of the close method, which closes an EntityManager. *调用close方法,这将关闭EntityManager。

*Invocation of the clear method, which clears an EntityManager's persistence context. *调用clear方法,该方法清除EntityManager的持久性上下文。

*Rolling back a transaction - either by invocation of rollback or by a commit failure. *回滚事务-通过调用回滚或提交失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM