JPA - Hibernate Entity Manager
Last Updated :
02 Apr, 2024
JPA in Java persistence can be defined as the Java Persistence API, and it plays an important role in communicating between Java objects and related databases Hibernate is one of the most popular JPA implementations.
JPA and Hibernate Entity Manager
JPA is a specification for managing relational data in Java applications and can provide a variety of interfaces and annotations to perform data manipulation by providing Java objects to database tables.
Hibernate Entity Manager is a JPA service that can be specifically provided by the Hibernate framework and can act as an intermediary between Java objects and the underlying database This JPA can handle CRUD operations, transactions, and entity management of applications.
Step-by-Step Implementation of JPA Application with the Hibernate Entity Manager
We can develop the simple JPA application with the Hibernate Entity Manager for the CRUD operations.
Step 1: Setting up the project.
Create the new Java project in the IntelliJ Idea on creating the project select the template as the library build system as maven and click on the next button.

Step 2: Add the dependencies.
Add the dependencies of the Persistence and Hibernate into the project. Refer the below image for the better understanding.

Step 3: Open the pom.xml add the below dependency for the MYSQL database connectivity of the project.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
After the project creation completed, the file structure looks like the below image.

Step 4: Configuring persistence.xml
Open the persistence.xml for the configuring the JPA settings and it can include the database connection details and the entity mapping.
XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
version="3.0">
<persistence-unit name="hibernateDemo">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>dto.Student</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/example"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Step 5: Creating the Entity Class
Create the new Java Entity class named as Student for the representing the database entities and annotate such as the @Entity, @Id.
Java
package dto;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
// The Entity annotation specifies that the class is an entity and it is mapped to a database table
@Entity
public class Student {
// The Id annotation specifies the primary key of the entity
@Id
// GeneratedValue annotation provides the strategy for generating primary key values
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// Name of the student
private String name;
// Age of the student
private int age;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Step 6: Create the DTO class for performing CRUD Operations
Create the new java class named as StudentDTO and it can use the Hibernate Entity Manager to persist, retrieve, update and delete the entities from the database.
Java
package dto;
import jakarta.persistence.*;
import java.util.List;
// Data Access Object (DAO) class for handling Student entities
public class StudentDAO {
private EntityManagerFactory entityManagerFactory;
// Constructor to initialize the EntityManagerFactory
public StudentDAO() {
entityManagerFactory = Persistence.createEntityManagerFactory("hibernateDemo");
}
// Method to save a Student entity to the database
public void saveStudent(Student student) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(student);
transaction.commit();
entityManager.close();
}
// Method to find students by their name
public List<Student> findStudentByName(String name) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
TypedQuery<Student> query = entityManager.createQuery("SELECT s FROM Student s WHERE s.name = :name", Student.class);
query.setParameter("name", name);
return query.getResultList();
} finally {
entityManager.close();
}
}
// Method to update a Student entity in the database
public void updateStudent(Student student) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.merge(student);
transaction.commit();
entityManager.close();
}
// Method to delete a Student entity from the database
public void deleteStudent(Student student) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
// Check if the entity is managed by the EntityManager, and if not, merge it before removal
entityManager.remove(entityManager.contains(student) ? student : entityManager.merge(student));
transaction.commit();
entityManager.close();
}
}
Step 7: Handling the Transcations
Create the Java class named as MainApp and it can be managing the transactions using the EntityManager and EntityTransaction API provided by the JPA.
Java
import dto.Student;
import dto.StudentDAO;
import java.util.List;
public class MainApp {
public static void main(String[] args) {
// Instantiate the StudentDAO class
StudentDAO studentDAO = new StudentDAO();
// Create and save a new student
Student student = new Student();
student.setName("Mahesh");
student.setAge(25);
studentDAO.saveStudent(student);
// Create and save another student
Student student2 = new Student();
student2.setName("Eswar");
student2.setAge(22);
studentDAO.saveStudent(student2);
// Find students with the name "Eswar"
List<Student> students = studentDAO.findStudentByName("Eswar");
if (!students.isEmpty()) {
System.out.println("Found Students:");
for (Student s : students) {
System.out.println(s.getName());
}
} else {
System.out.println("No students found with the given name.");
}
}
}
Output:
Below we can see the output in console:

JPA EntityManager Methods
Methods
| Definitions
|
---|
persist(Object entity)
| This method can used to make the instance managed and persistent.
Usage: Use the persist to save the new entity into the database. Entity can be managed by the persistence context and any changes are made to it will be automatically synchronized with database upon the transaction commit.
|
merge(Object entity)
| This method can be used to merge the state of the given entity into current persistence context.
Usage: Use the merge to the update of the exisiting entity instance to the persistence context and it can returns the merged entity which can be the further used for the modification and sychronization with database.
|
remove(Object entity)
| This method can be used to remove the entity instance from the database.
Usage: Use the remove to delete the existing the instance from the database.
|
find(Class<T> entityClass, Object primaryKey)
| This method can be used to find the entity by its the primary key.
Usage: Use the find to retrieve the entity instance from the database on its the primary key value.It returns the entity instance.
|
getReference(Class<T> entityClass, Object primaryKey)
| This method can be similar to the find but it can returns the reference to the entity instead of the loading it immediately.
Usage: Use the getReference to the obtain refrenece to an the entity without actually loading it from the database.
|
flush()
| This method can be used to sychronize the persistence context with underlying the database.
Usage: Use the flush to force the EntityManager to the synchronize the changes are made to managed the entities with database.
|
detach(Object entity)
| This method can be used to the detach the entity instance from the persistence context.
Usage: Use the detach to the remove an entity from persistence context and it can effectively making it detached.
|
clear()
| This method can be used to clear the persistence context and it can be detaching all the managed entities.
Usage: Use the clear to remove all managed entities from persistence context.
|
Further Subtopics:
- JQPL (Java Persistence Query Language): JPQL can be defined as the query language similar to the SQL but the operations on entity objects instead of the database tables and it can allow the developers to write the platform independent queries using the entity attributes and relationships.
- Criteria API: The Criteria API can be defined as the programmatic approach for the building queries dynamically using the java codes and it can provide the type of safe way to the construct the queries without the writing SQL or JPQL strings explicitly.
- Mapping Inheritance Hierarchies: JPA can supports the different strategies for the mapping the inheritance hierarchies that can including the single table, joined and the table-per-class inheritance. Understanding these strategies is the crucial for the modeling complex object inheritance.
- Caching Strategies: Hibernate can offers the various caching strategies to the improve application performance by the reducing the database round trips and these can include the first level-cache and second-level cache.
Similar Reads
Hibernate - Component Mapping
In general, a student can have an address/employee can have an address. For these kind of requirements, we can follow Component mapping. It is nothing but a class having a reference to another class as a member variable. i.e. inside the 'student' class, we can have the 'address' class as a member va
8 min read
Hibernate - Map Mapping
In a java collection, a map stores elements in key-value pairs. It will not allow duplicate elements. The map interface allows the mapped contents as a set of keys(keys alone) and a collection of values(values alone) or a set of key-value mappings. java.util.HashMap will be useful to initialize an u
10 min read
Hibernate - Collection Mapping
Collection elements are much needed to have one-to-many, many-to-many, relationships, etc., Any one type from below can be used to declare the type of collection in the Persistent class. Persistent class from one of the following types: java.util.Listjava.util.Setjava.util.SortedSetjava.util.Mapjava
5 min read
Hibernate - @ManyToOne Annotation
@ManytoOne annotation in Hibernate is used to create a many-to-one relationship between two entities. The @ManyToOne annotation indicates that the many instances of one entity can be associated with only one instance of another entity. When we annotate a field of the method with @ManyToOne annotatio
4 min read
Hibernate - Query Language
polymorphicHibernate is a Java framework that makes it easier to create database-interactive Java applications. In HQL, instead of a table name, it uses a class name. As a result, it is a query language that is database-independent. Hibernate converts HQL queries into SQL queries, which are used to
4 min read
Hibernate - @ManyToMany Annotation
@ManyToMany annotation in Hibernate is used to obtain many-to-many relationships between two entities. It allows us to create a bidirectional relationship between two entities where each entity can be associated with another entity through multiple instances. Examples of @ManyToMany Annotation Examp
4 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question
4 min read
Hibernate - Many-to-One Mapping
Hibernate is an open-source, ORM(Object Relational Mapping) framework that provides CRUD operations in the form of objects. It is a non-invasive framework. It can be used to develop DataAcessLayer for all java projects. It is not server-dependent. It means hibernate code runs without a server and wi
5 min read
Hibernate - Mapping List
In Hibernate, in order to go for an ordered collection of items, mostly List is the preferred one, Along with List, we have different collection mapping like Bag, Set, Map, SortedSet, SortedMap, etc., But still in many places mapping list is the most preferred way as it has the index element and hen
3 min read
Hibernate - One-to-Many Mapping
Hibernate is used to increase the data manipulation efficiency between the spring application and the database, insertion will be done is already defined with the help of hibernating. JPA (Java persistence API) is like an interface and hibernate is the implementation of the methods of the interface.
5 min read