BerndGit BerndGit - 9 days ago 5
Java Question

Hibernate: detached of entities after commit()

I have recived the following error message in my code, althrough I never manually call the

detach()
command:

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.
(see here). So I assume that every
item
is automitically detached after this operation. Correct?

I suspect that this is the root cause of my issues. I want to trigger the
detach() / merge()
only explicitly. Is there a posiblity to change the settings, so that
EntityManager.getTransaction().commit()
does NOT cause an
detach()
?

Answer

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:

*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.

Comments