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 JPAJPA 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:.png)
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 UnitThe 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. EntityManagerThe 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. EntityManagerFactoryThe 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 LayerThe 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 );
Frequently Asked Questions – JPA ArchitectureQ. What are the advantages of JPA?The advantages of JPA are:
- Usable within both Java SE (Standard Edition) and EE (Enterprise Edition)
- Is a compatible, standard API for ORM.
Q. What are the features of JPA?The features of JPA are:
- Supports both dynamic & static queries in a SQL-like query language: JPQL (Jakarta Persistence Query Language)
- Is a POJO (Plain Old Java Object) Persistence API for ORM
- Supports the usage of pluggable persistence providers
Q. Who developed JPA?JPA was developed by Oracle, the globally famous tech giant which also releases Java Standard & Enterprise editions.
Q. What are the disadvantages of JPA?The disadvantages of JPA are:
- JPA needs an implementation from an Oracle vendor, as it’s not an exclusive product
- Becoming a JPA expert requires a lot of time & effort, of around 1 year
|