In this tutorial I will explain you how to manage Entities. You will learn about the JPA environment and the persistence which is responsible for managing the state of the Entity.
In the JPA environment Entities are managed by the entity manager which is the instance of javax.persistence.EntityManager. In the JPA Environment each EntityManager is associated with the persistence content. The persistence context manages the set of entities and each entity is identified by a primary key. This primary key is the primary of the mapped table.
The persistence context defines the scope under which particular entity is managed in other words it is created, persisted and removed. The EntityManager defines the methods for accessing/persisting the entity within the persistence context.
The EntityManager Interface
The EntityManager is an interface which is packaged in the javax.persistence package. It provides the methods for creating, removing and finding the entity by primary key. It also allows to run the various types of queries (such as JPQL, native query etc..) against the database.
In your Java SE based application you can get the EntityManager instance through following code:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("unit-name"); EntityManager em = factory.createEntityManager();
After getting the EntityManager instance you can perform CRUD operations on the entities.
Here are the important method of EntityManager interface:
persist(Object entity): This method is used to persist a managed Entity.
remove(Object entity): This method is used to remove an Entity from the persistence context.
merge(T entity): This method is used to save the current state of Entity to the persistence context.
find(Class<T> entityClass, Object primaryKey): This method is used to load an Entity based on its primary key.
Entity Manager Types
There are two types of EntityManagers Container-Managed Entity Managers and Application-Managed Entity Managers.
Container-Managed Entity Managers
The Container-Managed Entity Managers is available in the JEE based applications and you can get the instance of the EntityManager with the help of @PersistenceContext annotation.
Here is the code to get the EntityManager:
@PersistenceContext EntityManager em;
Application-Managed Entity Managers
The application managed Entity managers and use in Java SE based project. You can get the instance of EntityManager through EntityManagerFactory interface. Here is the complete code to get the EntityManager in the Java SE project:
EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); EntityManager em = factory.createEntityManager();
You can also use the EntityManager to find the entities using JPQL and Native queries.