JPA

Jakarta Persistence API - the standard for mapping Java objects to relational databases.

Overview

JPA (Jakarta Persistence API, earlier called Java Persistence API) is a specification that lets you work with database rows as ordinary Java objects. You describe the mapping with annotations, and a JPA provider such as Hibernate generates the SQL for you.

Understanding JPA gives you a solid foundation that works with Hibernate, EclipseLink and Spring Data JPA alike.

Where it is used

  • CRUD applications
  • Spring Boot services using Spring Data JPA
  • Jakarta EE applications
  • Reducing hand-written SQL and JDBC code

A simple entity

@Entity
@Table(name = "student")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    private String email;

    // getters and setters
}
TypedQuery<Student> q = em.createQuery(
    "SELECT s FROM Student s WHERE s.name LIKE :n", Student.class);
q.setParameter("n", "A%");
List<Student> result = q.getResultList();

What you will cover

The key topics and features of JPA

Entities & Annotations

@Entity, @Table, @Id, @GeneratedValue and @Column to describe your data.

Relationships

One-to-one, one-to-many, many-to-one and many-to-many mappings.

JPQL & Criteria API

Query using objects and attributes instead of tables and columns.

EntityManager

Persist, find, merge and remove entities inside a persistence context.

Transactions

Keep data consistent with commit and rollback.

Inheritance Mapping

Map class hierarchies to tables with single-table or joined strategies.