Tutorial

JPA EntityManager - Hibernate EntityManager

Published on August 3, 2022
author

Pankaj

JPA EntityManager - Hibernate EntityManager

JPA EntityManager is at the core of Java Persistence API. Hibernate is the most widely used JPA implementation.

JPA EntityManager

  • One of the most important aspect of a program is connection with database. Database connection and transaction with database is considered as most expensive transaction. ORM is a very important tool in this regard. ORM helps in representing relations of database in terms of java objects.
  • ORM consists of two concepts object-oriented and relational programming.
  • Hibernate is an ORM framework where programmer describes the way objects are represented in database. Hibernate handles the conversion automatically.
  • Hibernate provides implementation of JPA interfaces EntityManagerFactory and EntityManager.
  • EntityManagerFactory provides instances of EntityManager for connecting to same database. All the instances are configured to use the same setting as defined by the default implementation. Several entity manager factories can be prepared for connecting to different data stores.
  • JPA EntityManager is used to access a database in a particular application. It is used to manage persistent entity instances, to find entities by their primary key identity, and to query over all entities.

JPA EntityManager Methods

JPA EntityManager is supported by the following set of methods. For better readability, I have not mentioned method arguments.

  1. persist - Make an instance managed and persistent.
  2. merge - Merge the state of the given entity into the current persistence context.
  3. remove - Remove the entity instance.
  4. find - Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there.
  5. getReference – returns and instance which is lazily fetched and will throw EntityNotFoundException when the instance is accessed for the first time.
  6. flush – Synchronizes the persistence context with the database.
  7. setFlushMode – set the flush mode for all the objects of the persistence context.
  8. getFlushMode – get the flush mode for all the objects of the persistence context.
  9. lock - Lock an entity instance that is contained in the persistence context with the specified lock mode type.
  10. refresh – it refreshes the state of the instance from the database also it will overwrite the changes to the entity.
  11. clear - Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.
  12. detach – this is similar to the clear method, only addition is the entity which previously referenced the detached object will continue to do so.
  13. contains – it checks if the managed entity belongs to the current persistence context.
  14. getLockMode – get the current lock mode for entity instance.
  15. setProperty – set an entity manager property or hint.
  16. getProperties – get the properties and hints associated with the entity manager.
  17. createQuery - Create an instance of Query for executing a Java Persistence query language statement.
  18. createNamedQuery - Create an instance of Query for executing a Java Persistence named query language statement.
  19. createNativeQuery - Create an instance of Query for executing a native sql statement.
  20. createNamedStoredProcedureQuery - Create an instance of StoredProcedureQuery for executing a stored procedure in the database.
  21. createStoredProcedureQuery - Create an instance of StoredProcedureQuery for executing a stored procedure in the database.
  22. joinTransaction - Indicate to the entity manager that a JTA transaction is active. This method should be called on a JTA application managed entity manager that was created outside the scope of the active transaction to associate it with the current JTA transaction.
  23. isJoinedToTransaction – it determines if the entityManager is linked to the current transaction.
  24. unwrap - Return an object of the specified type to allow access to the provider-specific API
  25. getDelegate – return the provider object for the entityManager.
  26. close – close an application-managed entityManager.
  27. isOpen – determine if the entityManager is open.
  28. getTransaction - Return the resource-level EntityTransaction object.
  29. getEntityManagerFactory – provides the entity manager factory for the entity manager.
  30. getCriteriaBuilder - Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.
  31. getMetamodel - Return an instance of Metamodel interface for access to the metamodel of the persistence unit.
  32. createEntityGraph - Return a mutable EntityGraph that can be used to dynamically create an EntityGraph.
  33. getEntityGraph – returns a named entityGraph

Let’s look at some of the methods through EntityManager example project.

Hibernate EntityManager Example

We will create a maven project for JPA Hibernate EntityManager example, below image illustrates different component of our Eclipse project. JPA EntityManager, Hibernate EntityManager example I am using MySQL for database, below query will create our test table.

CREATE TABLE `employee` (
  `employee_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `employee_name` varchar(32) NOT NULL DEFAULT '',
  PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

It’s a very simple table but suits for our example to showcase EntityManager usage.

Hibernate Maven Dependencies

We will have to include Hibernate and MySQL java driver dependencies in our pom.xml file. I am using Hibernate 5 with latest version of mysql-connector-java jar.

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

	<groupId>com.journaldev.hibernate</groupId>
	<artifactId>hibernate-entitymanager</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>hibernate-entitymanager</name>
	<url>https://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>

Hibernate persistence.xml

The most important part of using hibernate is to provide persistence.xml file. This xml holds the configuration for connecting to database.

<persistence xmlns="https://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/persistence
             https://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
	version="2.1">

	<persistence-unit name="persistence">
		<description>Hibernate Entity Manager Example</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="javax.persistence.jdbc.user" value="journaldev" />
			<property name="javax.persistence.jdbc.password" value="journaldev" />
			<property name="hibernate.show_sql" value="true" />
		</properties>

	</persistence-unit>

</persistence>
  • hibernate.show_sql is used to tell hibernate to print sql queries into log files or console.
  • The most important configuration is provider class i.e. org.hibernate.jpa.HibernatePersistenceProvider. This is how Hibernate is hooked into our application to be used as JPA implementation.
  • There are properties to connect to your database and driver to use.
  • It is important to note that persistence.xml should be placed in the META-INF directory, as you can see from the project image.

Hibernate Entity Bean

We will now create an Employee.java class that will correspond to the employee table created in the database. The employee class is declared as entity using the @Entity annotation.

package com.journaldev.jpa.hibernate.model;

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 [employeeId=" + employeeId + ", name=" + name + "]";
	}

}

Now it’s time to create our main program and run some queries using EntityManager methods.

package com.journaldev.jpa.hibernate.main;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.journaldev.jpa.hibernate.model.Employee;

public class App {
	public static void main(String[] args) {
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
		EntityManager entityManager = entityManagerFactory.createEntityManager();

		System.out.println("Starting Transaction");
		entityManager.getTransaction().begin();
		Employee employee = new Employee();
		employee.setName("Pankaj");
		System.out.println("Saving Employee to Database");

		entityManager.persist(employee);
		entityManager.getTransaction().commit();
		System.out.println("Generated Employee ID = " + employee.getEmployeeId());

		// get an object using primary key.
		Employee emp = entityManager.find(Employee.class, employee.getEmployeeId());
		System.out.println("got object " + emp.getName() + " " + emp.getEmployeeId());

		// get all the objects from Employee table
		@SuppressWarnings("unchecked")
		List<Employee> listEmployee = entityManager.createQuery("SELECT e FROM Employee e").getResultList();

		if (listEmployee == null) {
			System.out.println("No employee found . ");
		} else {
			for (Employee empl : listEmployee) {
				System.out.println("Employee name= " + empl.getName() + ", Employee id " + empl.getEmployeeId());
			}
		}
		// remove and entity
		entityManager.getTransaction().begin();
		System.out.println("Deleting Employee with ID = " + emp.getEmployeeId());
		entityManager.remove(emp);
		entityManager.getTransaction().commit();

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

	}
}
  1. Persistence.createEntityManagerFactory will provide EntityManagerFactory instance using the persistence-unit that we have provided in the persistence.xml file
  2. entityManagerFactory.createEntityManager() will create EntityManager instance for us to use. Every time we call createEntityManager() method, it will return a new instance of EntityManager.
  3. entityManager.getTransaction().begin() method first pulls the transaction from current persistence context and then begins the transaction using begin() method.
  4. entityManager.persist(employee) is used to persist the employee object in the database.
  5. entityManager.getTransaction.commit() method is used to fetch the transaction and then to commit the same transaction. This will commit all the changes to database.
  6. entityManager.find() is used to find an entity in the database using primary key.
  7. If you want to write a custom query, we can use entityManager.createQuery() method for it. Important point to note here is that the createQuery() method will have name given in the entity class and not the actual table name.
  8. entityManager.remove() should be used only when we have to remove an entity from the database.
  9. entityManager.close() is used to close the entity manager. Similarly entityManagerFactory.close() is to close the EntityManagerFactory. We should close these resources as soon as we are done with them.

Below is the output produced from one sample run of above program.

Starting Transaction
Saving Employee to Database
Hibernate: insert into employee (employee_name) values (?)
Generated Employee ID = 11
got object Pankaj 11
Dec 07, 2017 1:05:23 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select employee0_.employee_id as employee1_0_, employee0_.employee_name as employee2_0_ from employee employee0_
Employee name= Test, Employee id 5
Employee name= Pankaj, Employee id 6
Employee name= Pankaj, Employee id 11
Deleting Employee with ID = 11
Hibernate: delete from employee where employee_id=?

Notice how the employee id is generated when it’s saved into database and then mapped back to the object. Also notice the sql queries getting printed into console. Note that Hibernate will create more logs but I haven’t put them here for maintaining readability. That’s all for JPA EntityManager and it’s example with hibernate implementation. You can download the final Hibernate EntityManager example project from below link.

Download JPA Hibernate EntityManager Example Project

Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 1, 2019

Hi Pankaj, It’s great tutorial , Right now i am usin the above jpa approach(jpa-entitymanager-hibernate) & it’s working fine. Issue is that using jdbctemplate with jpa-entitymanager-hibernate, @Transactional annotation is not working. Can u please help me out for that https://www.journaldev.com/17379/jpa-entitymanager-hibernate, In this project you use jdbctemplate for insert data into table and enable transaction management and see the result… @Transaction is not working for JDBCTemplate. Please help me out as soon as possible.

- Saurabh Tiwari

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Featured on Community

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more