JPA Entity Manager
Following 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.
- 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 - An EntityManager is an interface
- createEntityManager() method - It creates new application-managed EntityManager
3) Intializing an entity manager.
- 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.
- persist() - This method is used to make an instance managed and persistent. An entity instance is passed within this method.
5) Closing the transaction
6) Releasing the factory resources.
- close() - This method is used to releasing the factory resources.
In the next section, we will perform various operations on an entity such as: -