JPA Entity Manager

Followings are some of the important roles of an entity manager: -

The entity manager implements the API and encapsulates all of them within a single interface.

Entity manager is used to read, delete and write an entity.

An object referenced by an entity is managed by entity manager.

Steps to persist an entity object.

1) Creating an entity manager factory object

The EntityManagerFactory interface present in java.persistence package is used to provide an entity manager.

EntityManagerFactory emf=Persistence.createEntityManagerFactory("Student_details");  

Persistence - The Persistence is a bootstrap class which is used to obtain an EntityManagerFactory interface.

createEntityManagerFactory() method - The role of this method is to create and return an EntityManagerFactory for the named persistence unit. Thus, this method contains the name of persistence unit passed in the Persistence.xml file.


2) Obtaining an entity manager from factory.

EntityManager em=emf.createEntityManager();  

EntityManager - An EntityManager is an interface

createEntityManager() method - It creates new application-managed EntityManager


3) Intializing an entity manager.

em.getTransaction().begin();  

getTransaction() method - This method returns the resource-level EntityTransaction object.

begin() method - This method is used to start the transaction.


4) Persisting a data into relational database.

em.persist(s1);  

persist() - This method is used to make an instance managed and persistent. An entity instance is passed within this method.


5) Closing the transaction

em.getTransaction().commit();  


6) Releasing the factory resources.

emf.close();  

em.close();  

close() - This method is used to releasing the factory resources.


Entity Operations

In the next section, we will perform various operations on an entity such as: -

  1. Inserting an Entity
  2. Finding an Entity
  3. Updating an Entity
  4. Deleting an Entity