Spring Boot JPA (Java Persistence API) – Complete Notes

1. What is JPA?

JPA (Java Persistence API) is a Java specification used to manage relational data in Java applications.

It provides a standard way to map Java objects to database tables.

Spring Boot uses Hibernate as the default JPA implementation.

Java Object  ↔  JPA/Hibernate  ↔  Database Table

Example

Java ClassDatabase Table
User.javauser
Product.javaproduct
Order.javaorders

2. Why Use JPA?

Without JPA (JDBC):

With JPA:

3. ORM (Object Relational Mapping)

ORM maps Java objects to database tables.

JavaDatabase
ClassTable
ObjectRow
FieldColumn
@Entity
public class Student {

    @Id
    private Long id;

    private String name;
}

4. JPA Architecture

Application
     |
Spring Data JPA
     |
JPA Specification
     |
Hibernate (Implementation)
     |
JDBC
     |
Database
LayerResponsibility
ApplicationBusiness Logic
Spring Data JPARepository abstraction
JPASpecification
HibernateORM implementation
JDBCDatabase connectivity

5. Important JPA Annotations

AnnotationPurpose
@EntityMarks class as database table
@TableCustom table name
@IdPrimary key
@GeneratedValueAuto ID generation
@ColumnCustomize column
@TransientIgnore field
@TemporalDate mapping

6. Entity Example

import jakarta.persistence.*;

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

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

    @Column(name="student_name")
    private String name;

    private String email;

}

7. JPA Repository (Spring Data JPA)

public interface StudentRepository 
        extends JpaRepository<Student, Long> {
}

Automatically provides:

8. Common CRUD Operations

studentRepository.save(student);
Student student = studentRepository.findById(1L).orElse(null);
List<Student> students = studentRepository.findAll();
studentRepository.deleteById(1L);

9. Derived Query Methods

public interface StudentRepository 
        extends JpaRepository<Student, Long> {

    List<Student> findByName(String name);

    List<Student> findByEmail(String email);

    List<Student> findByNameAndEmail(String name, String email);
}
SELECT * FROM students WHERE name = ?

10. Custom Query using @Query

@Query("SELECT s FROM Student s WHERE s.name = :name")
List<Student> getStudentsByName(String name);
@Query(value="SELECT * FROM students WHERE name = :name", 
       nativeQuery = true)
List<Student> getStudentsNative(String name);

11. JPA Relationships

RelationshipDescription
OneToOneOne record linked to one
OneToManyOne record → many
ManyToOneMany → one
ManyToManyMany ↔ many

12. One-to-Many Example

Student
   |
   | 1
   |
   |------ * Courses
@Entity
public class Student {

    @Id
    private Long id;

    @OneToMany(mappedBy = "student")
    private List<Course> courses;
}
@Entity
public class Course {

    @Id
    private Long id;

    @ManyToOne
    private Student student;
}

13. application.properties Configuration

spring.datasource.url=jdbc:mysql://localhost:3306/springdb
spring.datasource.username=root
spring.datasource.password=root

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

14. JPA Entity Lifecycle

New (Transient)
      |
      v
Managed (Persistent)
      |
      v
Detached
      |
      v
Removed

15. Advantages of Spring Data JPA

16. Disadvantages

17. Real World Example Architecture

Controller
     |
Service Layer
     |
Repository Layer (JPA)
     |
Hibernate
     |
Database
UserController
     |
UserService
     |
UserRepository (JpaRepository)
     |
MySQL

18. Best Practices

@Transactional
public void saveStudent(Student student){
    studentRepository.save(student);
}

19. Pagination Example

Page<Student> page =
        studentRepository.findAll(PageRequest.of(0,5));
ParameterMeaning
0Page number
5Records per page

20. Summary

Spring Boot JPA simplifies database operations by providing:


Entity Management in Spring Boot JPA

1. What Does “Entity Managed by JPA” Mean?

In Spring Boot JPA, an Entity is a Java object that is managed by the JPA persistence context.

When an entity is managed, JPA automatically:

Java Object (Entity)
        |
        v
Persistence Context (EntityManager)
        |
        v
Database Table

2. What is an Entity?

An Entity is a Java class mapped to a database table.

import jakarta.persistence.*;

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

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

    private String name;

    private String email;
}
Java EntityDatabase
Student classstudents table
idprimary key
namecolumn
emailcolumn

3. Who Manages the Entity?

EntityManager
        |
Hibernate (JPA Implementation)
        |
Database

In Spring Boot we usually interact through:

JpaRepository
        |
Spring Data JPA
        |
EntityManager
        |
Hibernate

4. Entity Lifecycle States

Transient  →  Persistent  →  Detached  →  Removed

Transient State

Student student = new Student();
student.setName("John");

Persistent State

studentRepository.save(student);

JPA now tracks changes automatically.

student.setName("David");

Hibernate will execute:

UPDATE students SET name='David' WHERE id=1

Detached State

The entity was previously managed but is no longer attached to the persistence context.

student.setName("Alex"); // not automatically saved

To reattach:

entityManager.merge(student);

Removed State

studentRepository.delete(student);
DELETE FROM students WHERE id=1

5. Persistence Context

The persistence context is a memory area where JPA manages entities.

Persistence Context
---------------------------
| Student id=1            |
| Student id=2            |
| Student id=3            |
---------------------------

6. Dirty Checking

JPA automatically detects changes made to managed entities.

Student student = studentRepository.findById(1L).get();
student.setName("Mike");

At transaction commit:

UPDATE students SET name='Mike' WHERE id=1

7. Transaction Role

@Transactional
public void updateStudent() {

    Student student = studentRepository.findById(1L).get();
    student.setName("Robert");

}
Start Transaction
        |
Load Entity
        |
Modify Entity
        |
Dirty Checking
        |
Commit Transaction
        |
Update Database

8. EntityManager vs JpaRepository

FeatureEntityManagerJpaRepository
LevelLow-level APIHigh-level abstraction
Code requiredMoreLess
UsageUsed internallyUsed by developers

9. Real World Flow

Controller
     |
Service
     |
Repository (JpaRepository)
     |
EntityManager
     |
Hibernate
     |
Database

10. Summary


How JDBC Connection is Managed Inside Spring Boot JPA

1. High-Level Flow

Application Code
       |
Spring Data JPA Repository
       |
EntityManager
       |
Hibernate
       |
JDBC
       |
HikariCP (Connection Pool)
       |
Database

Spring Boot automatically handles creating, reusing, and closing JDBC connections.

2. Key Components

ComponentResponsibility
DataSourceProvides JDBC connections
Connection PoolReuses database connections
HibernateGenerates and executes SQL
EntityManagerManages persistence context
Transaction ManagerControls transactions

3. DataSource Configuration

spring.datasource.url=jdbc:mysql://localhost:3306/springdb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Spring Boot automatically creates a DataSource and manages JDBC connections.

4. Connection Pool (HikariCP)

Hikari Connection Pool
---------------------------
| Connection 1            |
| Connection 2            |
| Connection 3            |
| Connection 4            |
---------------------------

Instead of creating new connections every time, Spring Boot reuses existing ones.

5. How Hibernate Uses JDBC

Connection connection = dataSource.getConnection();

PreparedStatement ps =
    connection.prepareStatement("SELECT * FROM students");

ResultSet rs = ps.executeQuery();

This code is executed internally by Hibernate. Developers normally do not write it.

6. Transaction Management

@Transactional
public void updateStudent() {

    Student student = repository.findById(1L).get();
    student.setName("David");

}
Start Transaction
       |
Get JDBC Connection from Pool
       |
Execute SQL
       |
Commit Transaction
       |
Return Connection to Pool

7. Traditional JDBC Steps vs Spring Boot

JDBC StepHandled By
Register driverSpring Boot Auto Configuration
Create connectionDataSource
Connection poolingHikariCP
Create statementHibernate
Execute queryHibernate
Map ResultSet to EntityHibernate ORM
Close connectionHikariCP

8. Internal Execution Flow

studentRepository.findAll()
        |
Spring Data JPA
        |
EntityManager
        |
Hibernate generates SQL
        |
DataSource provides connection
        |
HikariCP connection pool
        |
JDBC executes query
        |
Entities returned

9. Key Takeaways