Architecture & DesignCreate Entity Manager in JPA Tutorial

Create Entity Manager in JPA Tutorial

The Entity Classes

It is easy to transform a POJO into an entity class via annotation. In fact, a single annotation, @Entity, is enough to designate any POJO as an entity class. For example, examine a regular class such as follows:

public class Book {   private int id;
   private String title;
   private String publisher;
   public Book() {}
   public Book(int id, String title, String publisher) { = id;
      this.title = title;
      this.publisher = publisher;

   public int getId() { return id; }
   public void setId(int id) { = id;}
   public String getTitle() {return title; }
   public void setTitle(String title)  { this.title = title; }
   public String getPublisher()  { return publisher; }
   public void setPublisher(String publisher) { this.publisher =
      publisher; }

It is nothing but a Java Bean style of writing a class with three properties coupled with a set of getter and setter methods. We can turn this class into an entity class by using the @Entity annotation.

public class Book {
   private int id;

This annotation is a marker to denote that the class is an entity class to the persistence engine. Note that we have added another annotation, @Id. This annotation is used on a particular field or property to designate that it holds a persistence identity or the primary key of the databases as a unique identifying key of the table.

Understand that the two annotations, @Entity and @Id, are the minimal requirements to transform a POJO into an entity class. The JPA API provides numerous other annotations to fine tune many aspects of the entity class, but here we will not go into those details and instead focus on the functionality of the EntityManager class.

The Entity Manager

To persist an entity class into the database, there are specific API calls that need to be invoked. These API calls are encapsulated within a single interface, called EntityManager, and perform some intricate operations on the entities. The entity classes are actually delegated to this manager for actual persistence. The CRUD operations on the database are performed within the purview of entity manager and the designated entity classes are nothing but regular Java classes with some additional annotation.

The entity manager obtains a reference to an entity either as an argument to a method call or as an entity retrieved from the database. In any case, the EntityManager is the sole arbiter of the entity object. The set of managed entity instances within the purview of the entity manager, at any point of time, is called its persistence context. This means that an object that exists at a given instance of time within the persistent context is distinct with its persistent identity. For example, a Book instance with the persistent identity (say id=100) is distinct within the persistent context at any given point of time. There can be no other Book instance with the same id that can exist within the persistent context at that point. The persistence unit defines set of classes that are related or grouped by the application and is responsible for mapping to a single database.

The Persistent Provider

The implementation of the entity manager is dependent on the persistent provider and provides the backing engine that actually does all the dirty work. We can configure or manage the type of specific objects and manipulate read/write operations to the underlying database. The engine supplied by the provider is responsible for the entire Java Persistence API, such as implementing the EntityManager, query classes, and SQL generation.

The Entity Manager Factory

Entity managers are derived from factory interface called EntityManagerFactory. The configuration used by the entity manager is actually created by the entity manager factory. This definition is separately called a persistent unit. The persistent unit lays out both implicit and explicit settings, entity classes. This is used by the entity manager which again is derived from the EntityManagerFactory instance bound to the persistence unit. The persistent unit is given a name to make it distinguishable across the entity manager factory and to allow the application to have control over the configuration laid out in the specific persistent unit.

Once the entity manager factory is closed, all the entity manager associated with the factory also are closed.

How to Create an Entity Manager

Understand that entity managers are always derived in association with the entity manager factory. The factory determines the configuration parameters. The parameters determine the course of operation. This mechanism may not be obvious from the explicit operation seen by the user while running in a Java EE application server environment. While using the Java SE environment, we can use the bootstrap class called Persistence and invoke the createEntitymanagerFactory() method, which returns an instance of EntityManagerFactory for a specific persistence unit.

EntityManagerFactory emf = Persistence

Note that the name of the persistence unit in the code above is BookPU passed to the method. And the configuration of the persistence unit is as follows. The configuration typically is stored in an XML file called persistence.xml.

<persistence xmlns=""
   <persistence-unit name="BooksPU"
   <!-- Persistence provider -->
   <!-- Entity classes -->
      <property name="javax.persistence.jdbc.driver"
      value="org.h2.Driver" />
      <property name="javax.persistence.jdbc.url"
      value="jdbc:h2:mem:bookstore" />
      <property name="javax.persistence.jdbc.user"
      value="sa" />
      <property name="javax.persistence.jdbc.password"
      value="" />
      <property name="hibernate.dialect"
      <property name=""
      value="update" />
      <property name="show_sql"
      <property name="hibernate.temp.use_jdbc_metadata_defaults"
      <property name="hibernate.format_sql"
      <property name="hibernate.use_sql_comments"

Once the factory is created, we now may create the EntityManager instance and start working with the persistent entity classes.

EntityManager em = emf.createEntityManager();

Persisting the Entity

Now, we are in a position to persist the entity as follows:

Book book = new Book(101,"Effective Java","Addison-Wesley");


This is the basic idea behind the entity manager. We quickly skimmed over how to transform a POJO into an entity class and how to create an entity manager in the Java SE environment and the role of the entity manager factory in association with persistence in JPA. In a future article, we’ll see how to develop enterprise applications using the Java Persistence API.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories