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

If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen

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 which 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, committing, or rolling back the transaction.

4.2. Application Managed EntityManager

Conversely, the lifecycle of the EntityManager is managed by the application in 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();
}

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