Persistence top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

EntityManager is a part of the Java Persistence API. Chiefly, it implements the programming interfaces and lifecycle rules defined by the JPA 2.0 specification.

Moreover, we can access the Persistence Context, by using the APIs in EntityManager.

In this tutorial, we'll take a look at the configuration, types, and various APIs of the EntityManager.

2. Maven Dependencies

First, we need to include the dependencies of Hibernate:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.0.Final</version>
</dependency>

We will also have to include the driver dependencies, depending upon the database that we're using:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.13</version>
</dependency>

The hibernate-core and mysql-connector-java dependencies are available on Maven Central.

3. Configuration

Now, let's demonstrate the EntityManager, by using a Movie entity that corresponds to a MOVIE table in the database.

Over the course of this article, we'll make use of the EntityManager API to work with the Movie objects in the database.

3.1. Defining the Entity

Let's start by creating the entity corresponding to the MOVIE table, using the @Entity annotation:

@Entity
@Table(name = "MOVIE")
public class Movie {
    
    @Id
    private Long id;

    private String movieName;

    private Integer releaseYear;

    private String language;

    // standard constructor, getters, setters
}

3.2. The persistence.xml File

When the EntityManagerFactory is created, the persistence implementation searches for the META-INF/persistence.xml file in the classpath.

This file contains the configuration for the EntityManager:

<persistence-unit name="com.baeldung.movie_catalog">
    <description>Hibernate EntityManager Demo</description>
    <class>com.baeldung.hibernate.pojo.Movie</class> 
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value="root"/>
    </properties>
</persistence-unit>

To explain, we define the persistence-unit that specifies the underlying datastore managed by the EntityManager.

Furthermore, we define the dialect and the other JDBC properties of the underlying datastore. Hibernate is database-agnostic. Based on these properties, Hibernate connects with the underlying database.

4. Container and Application Managed EntityManager

Basically, there are two types of EntityManager: Container-Managed and Application-Managed.

Let's have a closer look at each type.

4.1. Container-Managed EntityManager

Here, the container injects the EntityManager in our enterprise components.

In other words, the container creates the EntityManager from the EntityManagerFactory for us:

@PersistenceContext
EntityManager entityManager;

This also means the container is in charge of beginning the transaction, as well as committing or rolling it back.

Similarly, the container is responsible for closing the EntityManager, so it's safe to use without manual cleanups. Even if we try to close a container-managed EntityManager, it should throw an IllegalStateException.

4.2. Application-Managed EntityManager

Conversely, the lifecycle of the EntityManager is managed by the application here.

In fact, we'll manually create the EntityManager. Furthermore, we'll also manage the lifecycle of the EntityManager we've created.

First, let's create the EntityManagerFactory:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog");

In order to create an EntityManager, we must explicitly call createEntityManager() in the EntityManagerFactory:

public static EntityManager getEntityManager() {
    return emf.createEntityManager();
}

Since we are responsible for creating EntityManager instances, it's also our responsibility to close themTherefore, we should close each EntityManager when we're done using them.

4.3. Thread-Safety

The EntityManagerFactory instances and, consequently, Hibernate's SessionFactory instances, are thread-safe. So it's completely safe in concurrent contexts to write:

EntityManagerFactory emf = // fetched from somewhere
EntityManager em = emf.createEntityManager();

On the other hand, the EntityManager instances are not thread-safe and are meant to be used in thread-confined environments. This means that each thread should obtain its instance, work with it, and close it at the end.

When using application-managed EntityManagers, it's easy to create thread-confined instances:

EntityManagerFactory emf = // fetched from somewhere 
EntityManager em = emf.createEntityManager();
// use it in the current thread

However, things get counter-intuitive when using container-managed EntityManagers. For example:

@Service
public class MovieService {

    @PersistenceContext // or even @Autowired
    private EntityManager entityManager;
    
    // omitted
}

It seems that one EntityManager instance should be shared for all operations. However, the container (JakartaEE or Spring) injects a special proxy instead of a simple EntityManager here. Spring, for example, injects a proxy of type SharedEntityManagerCreator

Every time we use the injected EntityManager, this proxy will either reuse the existing EntityManager or create a new one. Reuse usually occurs when we enable something like Open Session/EntityManager in View

Either way, the container ensures that each EntityManager is confined to one thread.

5. Hibernate Entity Operations

The EntityManager API provides a collection of methods. We can interact with the database, by making use of these methods.

5.1. Persisting Entities

In order to have an object associated with the EntityManager, we can make use of the persist() method :

public void saveMovie() {
    EntityManager em = getEntityManager();
    
    em.getTransaction().begin();
    
    Movie movie = new Movie();
    movie.setId(1L);
    movie.setMovieName("The Godfather");
    movie.setReleaseYear(1972);
    movie.setLanguage("English");

    em.persist(movie);
    em.getTransaction().commit();
}

Once the object is saved in the database, it is in the persistent state.

5.2. Loading Entities

For the purpose of retrieving an object from the database, we can use the find() method.

Here, the method searches by the primary key. In fact, the method expects the entity class type and the primary key:

public Movie getMovie(Long movieId) {
    EntityManager em = getEntityManager();
    Movie movie = em.find(Movie.class, new Long(movieId));
    em.detach(movie);
    return movie;
}

However, if we just need the reference to the entity, we can use the getReference() method instead. In effect, it returns a proxy to the entity:

Movie movieRef = em.getReference(Movie.class, new Long(movieId));

5.3. Detaching Entities

In the event that we need to detach an entity from the persistence context, we can use the detach() method. We pass the object to be detached as the parameter to the method:

em.detach(movie);

Once the entity is detached from the persistence context, it will be in the detached state.

5.4. Merging Entities

In practice, many applications require entity modification across multiple transactions. For example, we may want to retrieve an entity in one transaction for rendering to the UI. Then, another transaction will bring in the changes made in the UI.

We can make use of the merge() method, for such situations. The merge method helps to bring in the modifications made to the detached entity, in the managed entity, if any:

public void mergeMovie() {
    EntityManager em = getEntityManager();
    Movie movie = getMovie(1L);
    em.detach(movie);
    movie.setLanguage("Italian");
    em.getTransaction().begin();
    em.merge(movie);
    em.getTransaction().commit();
}

5.5. Querying for Entities

Furthermore, we can make use of JPQL to query for entities. We'll invoke getResultList() to execute them.

Of course, we can use the getSingleResult(), if the query returns just a single object:

public List<?> queryForMovies() {
    EntityManager em = getEntityManager();
    List<?> movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1")
      .setParameter(1, "English")
      .getResultList();
    return movies;
}

5.6. Removing Entities

Additionally, we can remove an entity from the database using the remove() method. It's important to note that, the object is not detached, but removed.

Here, the state of the entity changes from persistent to new:

public void removeMovie() {
    EntityManager em = HibernateOperations.getEntityManager();
    em.getTransaction().begin();
    Movie movie = em.find(Movie.class, new Long(1L));
    em.remove(movie);
    em.getTransaction().commit();
}

6. Conclusion

In this article, we have explored the EntityManager in Hibernate. We've looked at the types and configuration, and we learned about the various methods available in the API for working with the persistence context.

As always, the code used in the article is available over at Github.

Persistence bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!