Persistence Unit in JPA

Persistence Unit in JPA

In JPA, a  Persistence Unit  is a fundamental concept that defines a set of all entity classes that are managed together by the EntityManager in a specific persistence context. It is configured in a persistence.xml file, which is typically located in the META-INF directory of the classpath.

Persistence Unit in JPA

Key Aspects of a Persistence Unit:

  • 1.  Configuration :
    • Defined in the persistence.xml file.
    • Specifies various settings such as data source, JPA provider, entity classes, and properties related to the persistence context.
  • 2.  Entity Classes :
    • Lists the entity classes that are managed by the persistence unit.
  • 3.  Data Source :
    • Configures the database connection parameters.
  • 4.  JPA Provider :
    • Specifies the JPA implementation (e.g., Hibernate, EclipseLink).
  • 5.  Transaction Type :
    • Defines the transaction management type (JTA or RESOURCE_LOCAL).
  • 6.  Properties :
    • Includes additional configuration properties like caching, logging, and performance tuning settings.

Example

Let’s define a persistence unit in the persistence.xml file and use it in a simple JPA application.

Step 1: Define the persistence.xml File
xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                                 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="examplePU" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.example.demo.model.Student</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydb"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="password"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
    
</persistence>

Step 2: Define the Entity
java
package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private int age;

    // Constructors, getters, and setters

    public Student() {}

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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 3: Use the Persistence Unit in the Service
java
package com.example.demo.service;

import com.example.demo.model.Student;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.Transactional;
import java.util.List;

public class StudentService {

    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU");

    public void createStudent(Student student) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(student);
        em.getTransaction().commit();
        em.close();
    }

    public Student findStudent(Long id) {
        EntityManager em = emf.createEntityManager();
        Student student = em.find(Student.class, id);
        em.close();
        return student;
    }

    public void updateStudent(Student student) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.merge(student);
        em.getTransaction().commit();
        em.close();
    }

    public void deleteStudent(Long id) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Student student = em.find(Student.class, id);
        if (student != null) {
            em.remove(student);
        }
        em.getTransaction().commit();
        em.close();
    }

    public List<Student> findAllStudents() {
        EntityManager em = emf.createEntityManager();
        List<Student> students = em.createQuery("SELECT s FROM Student s", Student.class).getResultList();
        em.close();
        return students;
    }
}

Explanation of Example

  • persistence.xml :
    • Defines a persistence unit named examplePU with properties for database connection and Hibernate settings.
    • Includes the Student entity class.
  • Student Entity (Student.java) :
    • Defined as a JPA entity with ID, name, and age fields.
  • StudentService (StudentService.java) :
    • Provides methods to perform CRUD operations using EntityManager obtained from EntityManagerFactory.

Summary

A  Persistence Unit  in JPA:

  • Defines the configuration for managing entity classes.
  • Is specified in the persistence.xml file.
  • Includes settings for database connection, JPA provider, transaction management, and additional properties.
  • Ensures that entities within the persistence unit are managed in a cohesive manner by the EntityManager.