JPA EntityManager Example

JPA Entity Manager Example, we are going to find out how we can use the JPA Entity Manager to do operations on Database. It is the core of Java Persistence API. We are going to use Hibernate. Hibernate is one of the implementations of JPA. We generally use EntityManager in a JPA based application to interact with a persistence context.

The main advantage of using an EntityManager is that it does not bind  Spring to Hibernate. EntityManager is a part of JPA and any JPA based framework can be used for persistence.

JPA Entity Manager:-

  • It is used to interact withPersistence Context. The context consists a set of all entity instances.
  • The interface EntityManagerFactory is used by the application to obtain an application-managed Eentity Manager.
  • In ORM world entities are just like a table in the database. The EntityManager API  provides a set of API methods used to create, remove entity and query over entities.

JPA Entity Manager Example Code:-

Technologies Used:-

  • Java 1.8
  • Maven 3.3
  • Hibernate 5.2.6
  • Mysql

Project Dependencies:-


<project xmlns="" xmlns:xsi=""


	<name>Entity Manager</name>


		<!-- MySQL connector -->
		<!-- Hibernate 5.2.6 Final -->


How to Create an Entity Using JPA Annotations

We are going to create a simple bean with the name as Employee.This bean contains following properties.

  1. Id
  2. Name
package com.frugalis.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "EMPLOYEE")
public class Employee {
	private int employeeId;

	private String name;

	@Column(name = "EMPLOYEE_ID")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public int getEmployeeId() {
		return employeeId;

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;

	@Column(name = "EMPLOYEE_NAME")
	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String toString() {
		return "Employee [ID=" + employeeId + ", Name=" + name + "]";


As you can notice we are using annotation @Entity provided by JPA. This annotation identifies the POJO class as an Entity and to registers this class with the persistence context. Let’s configure our database before proceeding.

Configure Database for Persistence:-

We are going to create a file Persistence.xml and register the database for JPA.We are going to create a tag <persistance-unit>  andprovide a name for it under which all our configurations are defined.

<persistence xmlns=""

	<persistence-unit name="persistence">
		<description>JPA Entity Manager</description>

			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" />
			<property name="" value="update" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="root" />
			<property name="hibernate.show_sql" value="true" />



Save, Update, Retrieve and Delete an Entity Using  JPA Entity Manager:-

  1. We are going to create a persistence unit by providing persistence unit name we provided in the XML using createEntityManagerFactory() method.
  2. The entityManagerFactory creates an instance of entity manager using createEntityManager() method.
  3. Each operation done by entityManager is wrapped under a transaction.The entityManager provides transaction object for transaction management.
  4. Use begin () method on entityManager transaction object to start the transaction.
  5. Use commit() method to save the transaction and persist the changes.
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
		EntityManager entityManager = entityManagerFactory.createEntityManager();

		Employee employee = new Employee();

                // Save Entity
		System.out.println("Generated Employee ID = " + employee.getEmployeeId());

1. Retrieve an Entity using Primary Key:-

We got the employee Id from above step, hence using it to find the details and load from DB.

               //Reftrieve Enity from DB using Primary Key
		Employee emp = entityManager.find(Employee.class, employee.getEmployeeId());

2. Delete an Entity using JPA Entity Manager:-

We need to load Entity first from above step and then we remove the Entity.


Close the Entity manager after your task is done

// close the entity manager

3. Writing Custom Query Using JPA Entity Manager:-

We can also write a custom query to query the entities we are writing.The syntax is quite similar to SQL but the only difference is SQL works directly on database tables but the JQL works on Java classes and Instances.We can do all operations that we generally do using SQL.

Let’s take a look using simple Query against our Employee entity.

//Select Query
List<Employee> emplList= entityManager.createQuery("SELECT e FROM Employee e").getResultList();

List<Employee> emplList= entityManager.createQuery("SELECT UPPER( FROM Employee e").getResultList();

In order to write type safe queries, JPA has an introduced Criteria Query which uses entities to write queries.

Conclusion :-

JPA entity manager is used as an interface for database related operations and any ORM tools like hibernate and ibatis will use the interfaces to provide their own implementations.