Open In App

JPA – Hibernate Entity Manager

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Create New Java Project


Step 2: Add the dependencies.

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

Add dependencies


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.

Project Structure


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:

Output

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads