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):
<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):
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=true1. 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:
- JDBC (The Core Engine): The underlying Java API that actually executes SQL commands. Everything ultimately compiles down to JDBC.
- 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.
- 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.
- 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:
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 theidfield 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 (likenullable = falsewhich maps toNOT NULLin 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.
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>:
- Employee: The Entity class this repository manages.
- 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:
@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.
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.
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):
@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:
@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 usedFetchType.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".LAZYmeans: "Only fetch the employees from the database if I explicitly calldepartment.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.
@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.
- The class should be annotated as an
@Entityand mapped to a table namedcourses. - It must have a primary key field
idof typeLong, configured for automatic generation using the identity strategy. - It must include a
titlefield (String) that cannot be null and must be unique. - It must include an
instructorfield (String). - Define a one-to-many relationship with the
Reviewentity. The field should be aList<Review>namedreviews. This is the inverse (non-owning) side of the relationship and must be mapped by the corresponding field in theReviewentity. 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.
- The class should be annotated as an
@Entityand mapped to a table namedreviews. - It must have a primary key field
idof typeLong, with an identity generation strategy. - It must include a
ratingfield of typeInteger. - It must include a
commentfield (String) with a maximum length of 500 characters. - Define a many-to-one relationship with the
Courseentity. The field should be namedcourse. This is the owning side of the relationship and must define a foreign key column namedcourse_id.
Task 3: The CourseRepository
Create a Spring Data JPA repository interface named CourseRepository.
- The interface must extend
JpaRepository, specifying theCourseentity and its primary key type. - Define a method
findTopRatedCoursesthat accepts anIntegerparameter namedminRating. - Annotate this method with
@Queryto execute a custom JPQL query. The query should select allCourseentities where the average rating of their associated reviews is greater than or equal to the providedminRating.
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:
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:
CourseEntity:@OneToManydefines the relationship.mappedBy = "course"indicates that thecoursefield in theReviewentity manages this relationship, preventing the creation of a redundant join table.FetchType.LAZYis critical for performance, as it prevents Hibernate from loading all reviews every time a course is fetched.ReviewEntity:@ManyToOnemarks this as the owning side of the relationship.@JoinColumn(name = "course_id")explicitly defines the foreign key column in thereviewstable that links back to thecoursestable.CourseRepository: The@Queryannotation contains a JPQL query that operates on entities, not tables. It joinsCoursewith itsreviews, groups the results byCourse, and uses theHAVINGclause with theAVG()aggregate function to filter courses based on their average review rating.