Open In App

JPA - Architecture

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

JPA (Java Persistence API, sometimes also referred to as Jakarta Persistence API) is a tool to connect Java applications with databases for optimizing memory storage for data, thus providing a smoother User Experience (UX). In simple terms, JPA simplifies database access from within the Java application, by allowing to work with objects rather than SQL statements. JPA allows working with POJOs (Plain Old Java Objects) right from desktop apps, providing developers with an ORM (Object Relational Mapping) facility for managing relational data.

Architecture of JPA

JPA has 6 layers in its class-level architecture:

  1. Entity
  2. Persistence Unit
  3. EntityManager
  4. EntityManagerFactory
  5. Query Language
  6. Database Layer

Diagrammatic Representation of the Layers in JPA Class-level Architecture:

JPA---Architecture-(1)


1. Entity:

Defining the Entity class (the Entity class maps to the required table schema present in the linked database):

@Entity
@Table(name = "employee")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String department;
    
    // 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 String getDepartment()
      {
        return department;
      }
      
      public void setDepartment(String department)
      {
        this.department = department;
      }
      
}


Explanation of the annotations:

The keywords which starting with @ and containing useful inbuilt functionality are termed as annotations.

Annotation

Description

@Entity

Used to tell Java to treat this class as the Entity (or model) class

@Id

Sets the following variable as the primary key of the table in the database to which this Entity class is mapped

@GeneratedValue(strategy = GenerationType.IDENTITY)

Generates unique, auto-incrementing values for the variable mapped to the primary key of the table in the database

@Column

Specifies to the Java class that the following variable is mapped to the corresponding position column in the table of the mapped database

2. Persistence Unit

The Persistence Unit manages entity classes, typically defined in a persistence.xml file:

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.2">
    <persistence-unit name="myPersistenceUnit">
        <class>com.example.Employee</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydb"/>
            <property name="javax.persistence.jdbc.user" value="user"/>
            <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.MySQL8Dialect"/>
        </properties>
    </persistence-unit>
</persistence>


3. EntityManager

The EntityManager serves as the primary interface for interactions with the Persistence Context, allowing CRUD (Create-Read-Update-Delete) operations on entities:

Java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {
    public static void main(String[] args) {
        // Create EntityManagerFactory
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

        // Create EntityManager
        EntityManager em = emf.createEntityManager();

        // Begin transaction
        em.getTransaction().begin();

        // Create and persist a Department entity
        Department dept = new Department();
        dept.setName("HR");
        em.persist(dept);

        // Create and persist an Employee entity
        Employee emp = new Employee();
        emp.setName("John Doe");
        emp.setDepartment(dept);
        em.persist(emp);

        // Commit transaction
        em.getTransaction().commit();

        // Close EntityManager
        em.close();

        // Close EntityManagerFactory
        emf.close();
    }
}


4. EntityManagerFactory

The EntityManagerFactory is a factory for EntityManager instances. The createEntityManager() method creates a new EntityManager instance.

5. Java Persistence Query Language (JPQL)

JPQL is used to execute queries for CRUD operations on the database:

List<Employee> employees = em.createQuery("SELECT e FROM Employee e", Employee.class).getResultList();


6. Database Layer

The Database Layer contains the relational database that stores all the data of the application. The tables in the database are mapped to entity classes in the Java application.

SQL Code Example for creating a database and a table in it:

CREATE DATABASE mydb;

USE mydb;

CREATE TABLE users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE
);



    Article Tags :
    Practice Tags :

    Similar Reads