This blog article is part of a “series of blog articles” about common pitfalls using JPA and ways to avoid them. In this article, we describe the result of EntityManager.persist inside and outside of a transaction.
What is the result of
Employee emp = new Employee(...); em.persist(emp);
persist successfully makes the instance managed and persistent, but only inside of an active transaction. When called outside of a transaction the result depends on the type of the EntityManager:
- In case of a container-managed EntityManager (J2EE context) the
persistmethod will throw a
- In case of an application-managed EntityManager the method
persistis silent, but the passed instance is not persisted.
EntityExistsException indicates that an entity with the same id already exists. The exception may be thrown by method
persist or at flush or commit time.
Recommendation: Make sure the
persist method is called inside of an transaction.
You can find an example of this pitfall and its solution in the class PersisteOutsideTxExperiment in this project: https://github.com/akquinet/jpapitfalls.git.
You must log in to post a comment.