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:
- Entity
- Persistence Unit
- EntityManager
- EntityManagerFactory
- Query Language
- Database Layer
Diagrammatic Representation of the Layers in JPA Class-level Architecture:
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
);
Similar Reads
JSP Architecture JSP (Java Server Pages) uses a three-tier architecture with a client, web server, and database. When the client sends a request, the web server's JSP engine processes the JSP file by converting it into a servlet, compiling, and executing it. The generated HTML is sent back to the client. The followi
2 min read
Hexagonal Architecture in Java As per the software development design principle, the software which requires the minimum effort of maintenance is considered as good design. That is, maintenance should be the key point which an architect must consider. In this article, one such architecture, known as Hexagonal Architecture which m
6 min read
Hexagonal Architecture in Java As per the software development design principle, the software which requires the minimum effort of maintenance is considered as good design. That is, maintenance should be the key point which an architect must consider. In this article, one such architecture, known as Hexagonal Architecture which m
6 min read
J2EE Multitier Architecture A tier is an abstract concept that defines a group of technologies that provide one or more services to its clients. In multi-tier architecture, each tier contains services that include software objects, DBMS, or connectivity to legacy systems. IT departments of corporations employ multi-tier archit
4 min read
Architecture of a System Architecture is a critical aspect of designing a system, as it sets the foundation for how the system will function and be built. It is the process of making high-level decisions about the organization of a system, including the selection of hardware and software components, the design of interfaces
4 min read
Spring Framework Architecture The Spring framework is a widely used open-source Java framework that provides a comprehensive programming and configuration model for building enterprise applications. Its architecture is designed around two core principles: Dependency Injection (DI) Aspect-Oriented Programming (AOP)The Spring fram
7 min read