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(...);
em.persist(emp);

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: https://github.com/akquinet/jpapitfalls.git.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.