JPA Pitfalls (14): EntityManager.persist and Transactions

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 EntityManager.persist?

Employee emp = new Employee(...);

Method 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 persist method will throw a TransactionRequiredException.
  • In case of an application-managed EntityManager the method persist is silent, but the passed instance is not persisted.

An 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: