JPA EntityManager Example using Hibernate
November 21, 2023
This page will walk through JPA EntityManager
examples using Hibernate. EntityManager
is used to interact with persistence context. Using EntityManager
, 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 instances of entities in persistence context.
Here we will discuss
EntityManager
with some of its methods with examples.
Contents
1. Gradle
Find the gradle file to resolve the hibernate and MySQL JAR dependencies.build.gradle
apply plugin: 'java' apply plugin: 'eclipse' archivesBaseName = 'HibernateJPA' version = '1' repositories { mavenCentral() } dependencies { compile 'org.hibernate:hibernate-core:5.0.7.Final' compile 'org.hibernate:hibernate-entitymanager:5.0.7.Final' compile 'mysql:mysql-connector-java:5.1.31' }
2. 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.
3. 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
package com.concretepage; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class JPAUtility { private static final EntityManagerFactory emFactory; static { emFactory = Persistence.createEntityManagerFactory("com.concretepage"); } public static EntityManager getEntityManager(){ return emFactory.createEntityManager(); } public static void close(){ emFactory.close(); } }
<?xml version="1.0" encoding="UTF-8" ?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="com.concretepage"> <description>JPA Demo</description> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>com.concretepage.entity.Farmer</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/concretepage"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value=""/> </properties> </persistence-unit> </persistence>
4. Database Schema and Entity used in Demo
For theEntityManager
demo, we are using MySQL with following table.
Table:employee
CREATE TABLE `employee` ( `id` INT(11) NOT NULL, `city` VARCHAR(255) NULL DEFAULT NULL, `name` VARCHAR(255) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB;
package com.concretepage.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="employee") public class Employee { @Id @Column(name="id") private int id; @Column(name="name") private String name; @Column(name="city") private String city; public Employee() {} public Employee(int id, String name, String city) { this.id = id; this.name = name; this.city = city; } public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
5. persist()
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
package com.concretepage; import javax.persistence.EntityManager; import com.concretepage.entity.Employee; public class JPAWriteDemo { public static void main(String[] args) { EntityManager entityManager = JPAUtility.getEntityManager(); entityManager.getTransaction().begin(); Employee employee = new Employee(1, "Mahesh", "Varanasi"); entityManager.persist(employee); entityManager.getTransaction().commit(); entityManager.close(); JPAUtility.close(); System.out.println("Entity saved."); } }
6. find()
To fetch data from database usingEntityManager
, it provides find()
method. find()
method finds entity by primary key. We need to pass entity class type and id and find()
returns entity instance in persistence context.
JPASelectDemo.java
package com.concretepage; import javax.persistence.EntityManager; import com.concretepage.entity.Employee; public class JPASelectDemo { public static void main(String[] args) { EntityManager entityManager = JPAUtility.getEntityManager(); Employee emp = entityManager.find(Employee.class, new Integer(1)); System.out.println("Name:"+ emp.getName()+", City:"+ emp.getCity()); JPAUtility.close(); System.out.println("Done"); } }
Name:Mahesh, City:Varanasi Done
7. Updating Entity
To update data usingEntityManager
, we need to follow below steps.
1. Fetch entity using
find()
method. The returned entity instance will be in persistence context.
2. Begin
EntityManager
transaction.
3. Commit the transaction.
JPAUpdateDemo.java
package com.concretepage; import javax.persistence.EntityManager; import com.concretepage.entity.Employee; public class JPAUpdateDemo { public static void main(String[] args) { EntityManager entityManager = JPAUtility.getEntityManager(); Employee emp = entityManager.find(Employee.class, new Integer(1)); System.out.println("Name:"+ emp.getName()+", City:"+ emp.getCity()); //start updating entityManager.getTransaction().begin(); emp.setName("Krishna"); emp.setCity("Allahabad"); entityManager.getTransaction().commit(); emp = entityManager.find(Employee.class, new Integer(1)); entityManager.close(); JPAUtility.close(); System.out.println("Name:"+ emp.getName()+", City:"+ emp.getCity()); System.out.println("Entity updated."); } }
Name:Mahesh, City:Varanasi Name:Krishna, City:Allahabad Entity updated.
8. contains()
Usingcontains()
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
package com.concretepage; import javax.persistence.EntityManager; import com.concretepage.entity.Employee; public class JPAContainsDemo { public static void main(String[] args) { EntityManager entityManager = JPAUtility.getEntityManager(); Employee emp1 = entityManager.find(Employee.class, new Integer(1)); System.out.println(entityManager.contains(emp1)); Employee emp2 = new Employee(2, "Suresh", "New Delhi"); System.out.println(entityManager.contains(emp2)); entityManager.close(); JPAUtility.close(); System.out.println("Done"); } }
true false Done
9. detach()
Usingdetach()
method, we remove the given entity from persistence context. Before detach()
, changes made to entity which is not flushed, will not be synchronized with the database.
JPADetachDemo.java
package com.concretepage; import javax.persistence.EntityManager; import com.concretepage.entity.Employee; public class JPADetachDemo { public static void main(String[] args) { EntityManager entityManager = JPAUtility.getEntityManager(); Employee emp = entityManager.find(Employee.class, new Integer(1)); System.out.println("Contains(before detach):"+ entityManager.contains(emp)); //Detach entity entityManager.detach(emp); System.out.println("Contains(After detach):"+ entityManager.contains(emp)); entityManager.close(); JPAUtility.close(); System.out.println("Entity detached."); } }
Contains(before detach):true Contains(After detach):false Entity detached.
10. merge()
merge()
method merges the state of the given entity with current persistence context. The detached object can be merged using this method to current persistence context.
JPAMergeDemo.java
package com.concretepage; import javax.persistence.EntityManager; import com.concretepage.entity.Employee; public class JPAMergeDemo { public static void main(String[] args) { EntityManager entityManager = JPAUtility.getEntityManager(); //fetch entity Employee emp = entityManager.find(Employee.class, new Integer(1)); System.out.println("Name:"+emp.getName()+","+ "City: "+ emp.getCity()); System.out.println("Contains(before detach):"+ entityManager.contains(emp)); //detach entity entityManager.detach(emp); System.out.println("Contains(After detach):"+ entityManager.contains(emp)); //merge entity entityManager.getTransaction().begin(); emp.setName("Brahma"); emp.setCity("Kanpur"); emp = entityManager.merge(emp); entityManager.getTransaction().commit(); System.out.println("Contains(After merge):"+ entityManager.contains(emp)); System.out.println("Name:"+emp.getName()+","+ "City: "+ emp.getCity()); entityManager.close(); JPAUtility.close(); System.out.println("Entity merged."); } }
Name:Krishna,City: Allahabad Contains(before detach):true Contains(After detach):false Contains(After merge):true Name:Brahma,City: Kanpur Entity merged.
11. remove()
Usingremove()
method we can remove the entity instance from the database.
JPARemoveDemo.java
package com.concretepage; import javax.persistence.EntityManager; import com.concretepage.entity.Employee; public class JPARemoveDemo { public static void main(String[] args) { EntityManager entityManager = JPAUtility.getEntityManager(); Employee emp = entityManager.find(Employee.class, new Integer(1)); //start removing entityManager.getTransaction().begin(); entityManager.remove(emp); entityManager.getTransaction().commit(); entityManager.close(); JPAUtility.close(); System.out.println("Entity removed."); } }