This page will walk through JPA EntityManager and EntityManagerFactory example using hibernate with persist(), find(), contains(), detach(), merge() and remove() methods. EntityManager is used to interact with persistence context and EntityManagerFactory interacts with entity manager factory. Using EntityManager methods, we can interact with database. We can save, update and delete the data in database. The life cycle of entities are managed in persistence context. We can detach and merge the instance of entities in persistence context. Here we will discuss EntityManagerFactory and EntityManager and some of its methods with examples.

JPA EntityManager

JPA provides javax.persistence.EntityManager interface which is used to interact with database. The instance of EntityManager plays around persistence context. Persistence context is the set of entity instances where for any persistence entity identity, there is a unique entity instance. The lifecycle of entity instances are managed within the persistence context using EntityManager. We can detach and merge the entity instances within persistence context. Here on this page we will provide example to persist, fetch, update, detach, merge and remove entity instances. EntityManager provides javax.persistence.EntityTransaction using which we can begin and commit transaction.

JPA EntityManagerFactory

javax.persistence.EntityManagerFactory is an interface to interact with entity manager factory for the given persistence unit. After using entity manager factory, it should be closed. The instance of EntityManagerFactory is created by passing persistence-unit name of persistence.xml as arguments.
JPAUtility.java

JPA EntityManager.persist() Example

EntityManager provides persist() method to make entity managed and persist in database. We need to pass our entity instance to save data. The instance of EntityManager is obtained from EntityManagerFactory. EntityManager transaction should be started and committed in order to save entity.
JPAWriteDemo.java

JPA EntityManager.contains() Example

Using contains() method, we check if the entity is managed in current persistence context or not. It returns boolean value.
1. Fetch an entity using find() and pass it to contains() , we get true.
2. Detach the entity from current persistence context by using detach() and pass the instance to contains() method, we get false.
3. Call merge() method on the detached instance and now if we pass returned value to contains(), it will return true.
4. Create a new instance of entity and pass it to contains(), it returns false.
JPAContainsDemo.java