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 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.
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.
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.
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 – Hibernate Entity Manager
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.