JPA EntityManager is at the core of Java Persistence API. Hibernate is the most widely used JPA implementation.
EntityManagerFactory
and EntityManager
.JPA EntityManager is supported by the following set of methods. For better readability, I have not mentioned method arguments.
Let’s look at some of the methods through EntityManager example project.
We will create a maven project for JPA Hibernate EntityManager example, below image illustrates different component of our Eclipse project. 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.
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>
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.provider
class i.e. org.hibernate.jpa.HibernatePersistenceProvider
. This is how Hibernate is hooked into our application to be used as JPA implementation.persistence.xml
should be placed in the META-INF directory, as you can see from the project image.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();
}
}
Persistence.createEntityManagerFactory
will provide EntityManagerFactory instance using the persistence-unit
that we have provided in the persistence.xml
fileentityManagerFactory.createEntityManager()
will create EntityManager instance for us to use. Every time we call createEntityManager()
method, it will return a new instance of EntityManager.entityManager.getTransaction().begin()
method first pulls the transaction from current persistence context and then begins the transaction using begin() method.entityManager.persist(employee)
is used to persist the employee object in the database.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.entityManager.find()
is used to find an entity in the database using primary key.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.entityManager.remove()
should be used only when we have to remove an entity from the database.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.
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.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
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