Sobes.tech
Junior — Middle

Explain the differences between Persistent Context and EntityManager in the context of working with JPA.

sobes.tech AI

Answer from AI

In JPA, the Persistent Context is the environment where entities are managed. It represents a set of entity objects that are under the control of the EntityManager and are synchronized with the database. The Persistent Context provides a first-level cache where entities are stored in a managed state.

EntityManager is an interface that offers an API for working with the Persistent Context. Through the EntityManager, we can create, read, update, and delete entities, as well as manage the lifecycle of the Persistent Context (for example, opening and closing it).

In simpler terms:

  • Persistent Context is an internal mechanism that stores managed entities.
  • EntityManager is a tool (API) through which we interact with the Persistent Context.

Example:

EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
User user = em.find(User.class, 1L); // user is now in the Persistent Context
user.setName("New Name"); // changes are tracked
em.getTransaction().commit(); // changes are saved to the database
em.close();
Explain the differences between Persistent Context… - sobes.tech