JPA (Java Persistence API) is a Java specification that makes it easier to work with relational databases. It lets you map Java classes (entities) to database tables and manage data using simple APIs instead of writing complex SQL. In short, JPA acts as a bridge between Java objects and database records, simplifying database operations in Java applications.
Key features (significance) of JPA in Java
- Data Integrity: Ensures that data is accurate and consistent across the database.
- Allows Direct Mapping: Maps Java classes and fields directly to database tables and columns.
- Portable: Works across different databases without changing the code.
- Improves Productivity: Reduces boilerplate code and simplifies database operations.
- Easy to Implement: Provides a standard and simple API for CRUD operations and queries.
Core Concepts of JPA
To work effectively with JPA, it’s important to understand its core concepts:
- Entity
- EntityManager
- Persistence Context
- Criteria API
- JPQL (Java Persistence Query Language)
- Persistence Unit
1. Entity
An entity is a lightweight, persistent domain object that represents a table in a database. Each instance of an entity corresponds to a row in that table.
Importance: Entities are the core components in the JPA as they can define the structure of the data in a JPA application.
Example Entity Class:
Java
import javax.persistence.*;
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
// Constructors, getters, and setters
}
Explanation:
- @Entity: Marks the class as a JPA entity. JPA will manage this object for persistence.
- @Table(name = "employees"): Maps the entity to the employees table. Optional if table name is same as class name.
- @Id: Marks the primary key field.
- @GeneratedValue(strategy = GenerationType.IDENTITY): Database auto-generates the ID.
- @Column(name = "name"): Maps a field to a specific column in the database. Optional if field name matches column name.
2. EntityManager
The EntityManager is the core interface in JPA for interacting with the persistence context. It allows you to create, read, update and delete entities, as well as manage transactions.
Importance: It acts as the primary API for database interactions and ensures entities are persisted properly.
Example of Using EntityManager:
Java
import javax.persistence.*;
public class EmployeeDemo {
public static void main(String[] args) {
// Step 1: Create an EntityManagerFactory using the persistence unit defined in persistence.xml
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
// Step 2: Create an EntityManager from the factory
EntityManager em = emf.createEntityManager();
try {
// Step 3: Start a transaction
em.getTransaction().begin();
// Step 4: Create a new Employee entity
Employee emp = new Employee("John Doe", "[email protected]");
// Step 5: Persist (save) the entity to the database
em.persist(emp);
// Step 6: Commit the transaction to apply changes
em.getTransaction().commit();
// Optional: Print to confirm success
System.out.println("Employee saved successfully: " + emp);
} catch (Exception e) {
// If any error occurs, roll back the transaction
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
e.printStackTrace();
} finally {
// Step 7: Close EntityManager and EntityManagerFactory to release resources
em.close();
emf.close();
}
}
}
3. Persistence Context
The persistence context is a set of entity instances in which each entity identity is unique. It manages the lifecycle of entities and tracks changes made to them.
Importance: The persistence context ensures that entities are synchronized with the database and manages entity states such as managed, detached and removed.
4. Criteria API
The Criteria API is the programmatically defined the type safe query API used to define the queries for the entities and their persistent state of the JPA application.
Importance: It provides the platform for the creating dynamic queries where the structure of the query is not known until the runtime, unlike the JPQL which is static.
Example Criteria Query:
Java
import javax.persistence.*;
import javax.persistence.criteria.*;
import java.util.List;
public class CriteriaAPIDemo {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
EntityManager em = emf.createEntityManager();
try {
// Create CriteriaQuery to fetch employees with email ending in 'example.com'
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
Root<Employee> employee = cq.from(Employee.class);
cq.select(employee).where(cb.like(employee.get("email"), "%example.com"));
List<Employee> results = em.createQuery(cq).getResultList();
results.forEach(System.out::println);
} finally {
em.close();
emf.close();
}
}
}
5. JPQL (Java Persistence Query Language)
JPQL is the query language defined as the part of the JPA specification for the making queries against the entities stored in the database of JPA application.
Importance: JPQL can be designed to abstract database tables as the Java classes in the queries. Making it database agnostic and more integrated with the object oriented approach of the Java.
Example:
Java
// JPQL query to fetch all employees with email ending in 'example.com'
String jpql = "SELECT e FROM Employee e WHERE e.email LIKE '%example.com'";
List<Employee> results = em.createQuery(jpql, Employee.class).getResultList();
// Print results
results.forEach(System.out::println);
6. Persistence Unit
A persistence unit is a configuration in JPA that defines a set of entity classes managed by the EntityManager in your application.
- It tells JPA which entities should be tracked and persisted.
- It is configured in the persistence.xml file,
- which contains details like the database connection, entity classes and JPA provider.
Example in persistence.xml
Java
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.2">
<persistence-unit name="my-persistence-unit">
<!-- List of entity classes managed by this unit -->
<class>com.example.Employee</class>
<class>com.example.Department</class>
<!-- Database connection configuration -->
<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"/>
<!-- Hibernate properties -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Releted Articles: Architecture of JPA
Explore
Basics
OOPs & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java