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:-

pom.xml:-

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.frugalis.entity</groupId>
	<artifactId>Entity-Manager-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Entity Manager</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- MySQL connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
		<!-- Hibernate 5.2.6 Final -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src/main/java</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

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;

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

	private String name;

	@Id
	@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) {
		this.name = name;
	}

	@Override
	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="http://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
	version="2.1">

	<persistence-unit name="persistence">
		<description>JPA Entity Manager</description>
		<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

		<properties>
			<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="hibernate.hbm2ddl.auto" 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" />
		</properties>

	</persistence-unit>

</persistence>




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();

		entityManager.getTransaction().begin();
		Employee employee = new Employee();
		employee.setName("Sanjay");

                // Save Entity
		entityManager.persist(employee);
		entityManager.getTransaction().commit();
		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.

            entityManager.getTransaction().begin();
		entityManager.remove(emp);
		entityManager.getTransaction().commit();

Close the Entity manager after your task is done

// close the entity manager
 entityManager.close();
 entityManagerFactory.close();

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(e.name) 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.