Data Persistence: Talking to Databases with Spring Data JPA

9 min read

Most applications are useless if they forget everything the moment they are turned off. To retain data, we need a database. But bridging the gap between object-oriented Java code and relational databases (like PostgreSQL or MySQL) has historically been a headache.

In this module, we will explore how Spring Data JPA completely automates the process of saving, updating, and querying data, turning hundreds of lines of boilerplate code into simple interfaces.

Before we dive in, here is the standard boilerplate setup needed in your pom.xml and application.properties to get Spring Data JPA running with PostgreSQL.

Dependencies (pom.xml):

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Database Driver -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

Configuration (application.properties):

properties
spring.datasource.url=jdbc:postgresql://localhost:5432/my_database
spring.datasource.username=postgres
spring.datasource.password=supersecret
# Automatically creates or updates database tables based on your classes
spring.jpa.hibernate.ddl-auto=update
# Prints SQL to the console so you can see what Spring is doing
spring.jpa.show-sql=true

1. The Persistence Layer: JDBC vs Hibernate vs Spring Data

Definition: The persistence layer is the architectural section of an application responsible for storing and retrieving data from a database so that it survives beyond the application's runtime.

The Problem:
Databases speak SQL (Structured Query Language). Java speaks Objects. Historically, developers used the raw JDBC (Java Database Connectivity) API to connect the two. This required manually opening a database connection, writing raw SQL strings, manually mapping every single database column to a Java object field (user.setName(resultSet.getString("name"))), catching specific SQL exceptions, and manually closing the connection.

Writing raw JDBC for a system with 50 database tables is highly repetitive, difficult to maintain, and a great way to miss your deployment deadlines.

The Solution:
Object-Relational Mapping (ORM) and Spring Data JPA.

To understand the modern standard, you need to understand the hierarchy of tools working under the hood:

  1. JDBC (The Core Engine): The underlying Java API that actually executes SQL commands. Everything ultimately compiles down to JDBC.
  2. JPA (The Rulebook): Java Persistence API is a specification. It is just a set of rules and interfaces defining how Object-Relational Mapping should work in Java.
  3. Hibernate (The Worker): Hibernate is the most popular framework that implements JPA. It does the heavy lifting of translating your Java objects into SQL queries automatically.
  4. Spring Data JPA (The Manager): An abstraction layer built on top of JPA and Hibernate. It removes the need to write almost any database interaction code by automatically generating the Hibernate implementations based on simple interfaces you define.

Imagine you are running a busy pizza shop:

  • JDBC is you doing absolutely everything: taking the order, kneading the dough, baking the pizza, and driving the delivery car.
  • Hibernate is hiring a skilled chef. You give the chef a specific recipe (a Java Object), and they handle the oven (the database) to bake it.
  • Spring Data JPA is hiring a general manager. You just tell the manager, "Give me 5 pepperoni pizzas," and they handle communicating with the chef, the kitchen, and the delivery driver without you lifting a finger.

In the modern industry, we almost never write raw JDBC or raw Hibernate sessions. We interact purely with Spring Data JPA.


2. Entities and Primary Keys: Mapping Classes to Database Tables

Definition: An Entity is a lightweight Java class whose state is mapped to a table in a relational database.

The Problem:
A Java object only lives in the computer's RAM. A database does not know what a User class is; it only knows about a users table with rows and columns. We need a way to tell our framework exactly which Java class corresponds to which database table, and which variable corresponds to which column.

The Solution:
We use JPA annotations to mark up our Java classes. When the application starts, Hibernate reads these annotations and automatically creates or connects to the correct database tables.

Here is an industry-standard Entity setup:

java
import jakarta.persistence.*;

@Entity
@Table(name = "employees")
public class Employee {

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

    @Column(name = "first_name", nullable = false, length = 50)
    private String firstName;

    @Column(unique = true, nullable = false)
    private String email;

    // Constructors, Getters, and Setters omitted for brevity
}

Concept Breakdown:

  • @Entity: This annotation is mandatory. It registers this class as a database blueprint.
  • @Table(name = "employees"): Optional. If omitted, the table will be named exactly like the class (employee). Industry practice dictates using plural, snake_case names for tables.
  • @Id: Mandatory. Every relational database table requires a Primary Key to uniquely identify a row. This marks the id field as that key.
  • @GeneratedValue(strategy = GenerationType.IDENTITY): Tells the database to automatically generate and increment this ID (e.g., 1, 2, 3...) every time a new row is inserted.
  • @Column: Optional. Used to enforce constraints (like nullable = false which maps to NOT NULL in SQL) or to map the field to a different column name.

3. Repositories: The Magic Interfaces (JpaRepository)

Definition: A Repository is an interface that acts as a collection of domain objects in memory, abstracting away the database interactions needed to save, find, or delete them.

The Problem:
We have our Employee entity mapped to the database. But how do we actually save a new employee? Even with Hibernate, you would normally have to open a transaction, pass the object to the session, commit the transaction, and handle exceptions. Doing this for every entity is repetitive.

The Solution:
The JpaRepository interface.

By creating a simple interface that extends JpaRepository, Spring Boot will dynamically generate the database interaction code for you at runtime.

java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    // That's it. You don't write any implementation!
}

Concept Breakdown:

Notice the two types passed to JpaRepository<Employee, Long>:

  1. Employee: The Entity class this repository manages.
  2. Long: The data type of the Entity's Primary Key (@Id).

By merely declaring this empty interface, you instantly inherit powerful methods that you can inject into your Services:

java
@Service
public class EmployeeService {
    
    private final EmployeeRepository repository;

    public EmployeeService(EmployeeRepository repository) {
        this.repository = repository;
    }

    public void hireEmployee() {
        Employee emp = new Employee("John", "[email protected]");
        
        // Generates: INSERT INTO employees (first_name, email) VALUES (...)
        repository.save(emp); 
        
        // Generates: SELECT * FROM employees WHERE id = 1
        Employee found = repository.findById(1L).orElseThrow(); 
        
        // Generates: DELETE FROM employees WHERE id = 1
        repository.deleteById(1L); 
    }
}

4. Custom Queries: Derived Query Methods and the @Query Annotation

Definition: Custom queries are database instructions tailored to fetch specific subsets of data rather than basic Create, Read, Update, or Delete (CRUD) operations.

The Problem:
JpaRepository gives you findById() and findAll(). But what if you need to find an employee by their email? Or find all employees whose names start with "A"? These specific queries do not exist out of the box.

The Solution:
Derived Query Methods and the @Query annotation.

Derived Query Methods

Spring Data JPA has a built-in query builder. It acts like a translator. If you name your Java method following specific conventions, Spring parses the method name and automatically writes the SQL for you.

java
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    
    // Generates: SELECT * FROM employees WHERE email = ?
    Optional<Employee> findByEmail(String email);

    // Generates: SELECT * FROM employees WHERE first_name = ? AND email = ?
    List<Employee> findByFirstNameAndEmail(String firstName, String email);
}

The @Query Annotation

Derived query methods are amazing, but they have a breaking point. Imagine needing to find an active employee by their department, salary range, and start date. You would end up with a method named: findByDepartmentAndSalaryGreaterThanAndStartDateAfterAndStatus.

That is unreadable. When queries get complex, industry standard dictates using the @Query annotation to write JPQL (Java Persistence Query Language).

JPQL looks like SQL, but instead of querying database tables, you query Java Entities.

java
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    
    @Query("SELECT e FROM Employee e WHERE e.email = :email AND e.firstName LIKE %:prefix%")
    List<Employee> findCustomEmployees(String email, String prefix);
    
    // You can also write pure native SQL if needed
    @Query(value = "SELECT * FROM employees WHERE email = :email", nativeQuery = true)
    List<Employee> findUsingNativeSql(String email);
}

5. Relational Mapping: Handling One-to-Many and Many-to-Many Relationships

Definition: Relational mapping is the process of defining how different Entities connect to one another, mirroring foreign key constraints in a relational database.

The Problem:
Real-world data is connected. A Department has many Employees. In a standard SQL database, you link these by placing a department_id (Foreign Key) inside the employees table.
If we just store a Long departmentId in our Java Employee class, we lose the magic of ORM. We wouldn't be able to simply call employee.getDepartment().getName().

The Solution:
Relationship annotations: @OneToMany, @ManyToOne, and @ManyToMany.

The Most Common Setup: One-to-Many / Many-to-One

Relationships should usually be bidirectional. The "Many" side (Employee) holds the foreign key, so it is the "owner" of the relationship.

The "Many" Side (The Owner):

java
@Entity
public class Employee {
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Many Employees belong to One Department
    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "department_id") // Creates the foreign key column
    private Department department;
}

The "One" Side:

java
@Entity
public class Department {
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // One Department has Many Employees
    // 'mappedBy' tells Spring: "Look at the 'department' variable in the Employee class for the configuration."
    @OneToMany(mappedBy = "department") 
    private List<Employee> employees = new ArrayList<>();
}

Concept Breakdown & Industry Standards:

  • @JoinColumn: Tells the database the exact name of the foreign key column.
  • mappedBy: Placed on the non-owning side of the relationship. It prevents Hibernate from creating a redundant third table just to link the two entities.
  • The N+1 Query Problem (FetchType.LAZY): Notice we used FetchType.LAZY. By default, if you query 100 Departments, Hibernate might automatically fire 100 additional database queries to fetch the employees for every single department, even if you never asked for them! This is a massive performance killer known as the "N+1 Problem".
    • LAZY means: "Only fetch the employees from the database if I explicitly call department.getEmployees() in my code." Always use LAZY fetching in professional applications.

Many-to-Many

Used when many Students enroll in many Courses. Relational databases cannot handle this directly; they require a third "Join Table" in the middle. Spring Data JPA handles this automatically.

java
@Entity
public class Student {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToMany
    @JoinTable(
        name = "student_courses", // The hidden 3rd table
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "course_id")
    )
    private Set<Course> courses = new HashSet<>();
}

(Note: In heavily scaled industry applications, Many-to-Many is often avoided. Instead, developers manually create the middle Entity—e.g., Enrollment—and use two OneToMany relationships to have more control over the join table).


📚 References and Further Reading

Challenge

You are building the data persistence layer for an online learning platform. Your task is to model the relationship between Course and Review entities and create a custom repository query to find top-rated courses.

Task 1: The Course Entity

Define a JPA entity named Course.

  1. The class should be annotated as an @Entity and mapped to a table named courses.
  2. It must have a primary key field id of type Long, configured for automatic generation using the identity strategy.
  3. It must include a title field (String) that cannot be null and must be unique.
  4. It must include an instructor field (String).
  5. Define a one-to-many relationship with the Review entity. The field should be a List<Review> named reviews. This is the inverse (non-owning) side of the relationship and must be mapped by the corresponding field in the Review entity. To prevent performance issues, ensure this relationship is fetched lazily and that operations (like delete) are cascaded.

Task 2: The Review Entity

Define a JPA entity named Review.

  1. The class should be annotated as an @Entity and mapped to a table named reviews.
  2. It must have a primary key field id of type Long, with an identity generation strategy.
  3. It must include a rating field of type Integer.
  4. It must include a comment field (String) with a maximum length of 500 characters.
  5. Define a many-to-one relationship with the Course entity. The field should be named course. This is the owning side of the relationship and must define a foreign key column named course_id.

Task 3: The CourseRepository

Create a Spring Data JPA repository interface named CourseRepository.

  1. The interface must extend JpaRepository, specifying the Course entity and its primary key type.
  2. Define a method findTopRatedCourses that accepts an Integer parameter named minRating.
  3. Annotate this method with @Query to execute a custom JPQL query. The query should select all Course entities where the average rating of their associated reviews is greater than or equal to the provided minRating.

Expected result

Your code should correctly define two entities with a bidirectional one-to-many relationship and a repository with a custom JPQL query.

Correct Implementation:

java
import javax.persistence.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.ArrayList;

@Entity
@Table(name = "courses")
public class Course {

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

    @Column(nullable = false, unique = true)
    private String title;

    private String instructor;

    @OneToMany(mappedBy = "course", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Review> reviews = new ArrayList<>();
    
    // Getters and setters omitted for brevity
}

@Entity
@Table(name = "reviews")
public class Review {

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

    private Integer rating;

    @Column(length = 500)
    private String comment;

    @ManyToOne
    @JoinColumn(name = "course_id", nullable = false)
    private Course course;
    
    // Getters and setters omitted for brevity
}

public interface CourseRepository extends JpaRepository<Course, Long> {
    
    @Query("SELECT c FROM Course c JOIN c.reviews r GROUP BY c HAVING AVG(r.rating) >= :minRating")
    List<Course> findTopRatedCourses(@Param("minRating") Integer minRating);

}

Explanation:

  1. Course Entity: @OneToMany defines the relationship. mappedBy = "course" indicates that the course field in the Review entity manages this relationship, preventing the creation of a redundant join table. FetchType.LAZY is critical for performance, as it prevents Hibernate from loading all reviews every time a course is fetched.
  2. Review Entity: @ManyToOne marks this as the owning side of the relationship. @JoinColumn(name = "course_id") explicitly defines the foreign key column in the reviews table that links back to the courses table.
  3. CourseRepository: The @Query annotation contains a JPQL query that operates on entities, not tables. It joins Course with its reviews, groups the results by Course, and uses the HAVING clause with the AVG() aggregate function to filter courses based on their average review rating.
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.