Persisting Data with Spring Data JPA (and Schema Migrations)
Java & Spring Boot for Beginners · Part 10 of 14
- #Java
- #Spring Boot
- #Beginners
- #jpa
- #database
Everything the project has done so far — Part 8's first endpoint, Part 9's
full REST API — has lived in a List or Map sitting in memory. That was the
right call while we were learning controllers and routing: no setup, no
config, restart the app and see your change immediately. It has exactly one
problem, and it's a big one — restart the app and your data is gone too. A
real API needs a real database, and getting there is smaller than it sounds.
What changes, and what doesn't
The controller and service layers from Part 9 barely move. What changes is
what sits underneath them: instead of a hand-rolled List<Task> with methods
like findById written by hand, we get a real table, and Spring Data JPA
writes the CRUD methods for us.
Two dependencies, added to pom.xml (or build.gradle):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
H2 is an in-memory, zero-config database — perfect for learning and for
local development, useless for production, because its data disappears when
the process stops (yes, that's the same problem we're trying to fix — H2 just
delays it to app restart instead of every deploy). When this project is ready
to run for real, swapping the H2 dependency for org.postgresql:postgresql
and updating three lines in application.yml is the entire migration. That's
the point of an abstraction like JPA: the code in this post doesn't change
either way.
Turning a class into a table: @Entity
The Task class from earlier parts gets three annotations and stays
otherwise recognizable:
@Entity
@Table(name = "tasks")
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String description;
private LocalDate dueDate;
private boolean completed;
// getters and setters
}
@Entity tells Hibernate (the JPA implementation Spring Boot wires up for
you) that this class maps to a database table. @Table is optional — without
it, Hibernate would derive a table name from the class name — but naming it
explicitly avoids surprises later. @Id marks the primary key, and
@GeneratedValue(strategy = GenerationType.IDENTITY) tells the database to
assign the id itself (an auto-increment column), which is the simplest
choice for a learning project. Every other field maps to a column of the
same name by default, using Java's type to infer the column type — a
LocalDate becomes a DATE column, a boolean becomes... whatever your
database calls a boolean.
The repository: an interface that writes itself
This is the part that feels like magic the first time you see it. No implementation, just an interface:
public interface TaskRepository extends JpaRepository<Task, Long> {
List<Task> findByCompletedFalse();
List<Task> findByDueDateBefore(LocalDate date);
Optional<Task> findByIdAndCompletedFalse(Long id);
}
JpaRepository<Task, Long> — entity type, id type — already gives you
save, findById, findAll, deleteById, and a dozen others, fully
implemented, without a single line of code from you. The three methods above
are derived queries: Spring Data parses the method name at startup and
builds the SQL from it. findByCompletedFalse() becomes WHERE completed = false. findByDueDateBefore(date) becomes WHERE due_date < ?. This
convention covers a surprising amount of real querying before you ever need
@Query and a hand-written JPQL string.
Wiring it into the service
The service layer from Part 9 swaps its List field for an injected
repository, and its hand-written loops for repository calls:
@Service
public class TaskService {
private final TaskRepository taskRepository;
public TaskService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public Task createTask(Task task) {
return taskRepository.save(task);
}
public List<Task> getOpenTasks() {
return taskRepository.findByCompletedFalse();
}
public Task getTask(Long id) {
return taskRepository.findById(id)
.orElseThrow(() -> new NoSuchElementException("No task with id " + id));
}
}
Nothing about the controller changes at all — it still calls
taskService.createTask(...). That's the value of keeping the layers
separated from the start: swapping the storage mechanism touched exactly one
class.
Telling Spring where the database lives
application.yml (or .properties) points Spring at H2 and tells Hibernate
how to handle the schema while you're learning:
spring:
datasource:
url: jdbc:h2:mem:taskdb
driver-class-name: org.h2.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
h2:
console:
enabled: true
ddl-auto: update tells Hibernate to create or adjust tables from your
@Entity classes automatically — convenient for learning, and exactly the
setting you turn off once a real team and a real production database are
involved (more on that in a moment). show-sql: true prints every generated
query to the console, which is worth leaving on while you're learning to see
what your derived queries actually produce. The H2 console, enabled above, is
a browser-based table viewer at /h2-console — handy for confirming your
data is actually there.
Why ddl-auto: update doesn't survive contact with a team
Letting Hibernate manage your schema is fine solo, on a throwaway database. It falls apart the moment more than one person touches the project, or the database holds data you can't afford to lose: Hibernate's guesses about how to evolve a schema aren't always the change you intended, and "automatic" is the opposite of what you want for something as consequential as a schema change in production.
The standard fix is a migration tool — Flyway or Liquibase — where every
schema change is a versioned, checked-in file (V1__create_tasks_table.sql,
V2__add_priority_column.sql), applied in order, once, tracked in the
database itself. You're not there yet with this project, and ddl-auto is
the right tool for right now — just know its name, and know it has an
expiration date once this project (or any project) gets a second contributor
or a database worth protecting.
Spring Data JPA migrations with Flyway: what the switch looks like
When that day comes, the switch is smaller than it sounds, and none of the Spring Data JPA code in this post changes. The entity and the repository stay exactly as they are. What changes is who creates the table.
First, add Flyway next to the JPA starter. Spring Boot detects it and runs your migrations on startup, before Hibernate initializes:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
Then write the schema yourself, as a versioned SQL file in
src/main/resources/db/migration/. Here's the tasks table for the Task
entity above:
-- V1__create_tasks_table.sql
CREATE TABLE tasks (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title VARCHAR(255),
description VARCHAR(255),
due_date DATE,
completed BOOLEAN NOT NULL
);
Finally, take schema changes away from Hibernate. Switch ddl-auto from
update to validate:
spring:
jpa:
hibernate:
ddl-auto: validate
With validate, Hibernate never touches the schema. It only checks that the
tables match your @Entity classes, and the app refuses to start if they
don't. Rename completed in the SQL and forget the entity, and startup fails
with Schema-validation: missing column [completed] in table [tasks] instead
of breaking at runtime. The next change goes in a new file
(V2__add_priority_column.sql), never an edit to V1. Flyway records every
applied version in a flyway_schema_history table, so each file runs exactly
once per database. (On PostgreSQL, current Flyway versions also need the
org.flywaydb:flyway-database-postgresql module next to flyway-core.)
That's the minimum. Baselining an existing database, running migrations in
CI, and changing a schema without downtime are a topic of their own, covered
in Database Migrations with Flyway and Liquibase in Spring Boot
(Part 3 of the Spring Boot in Production series). On Spring Boot 4, the
dependency to add is spring-boot-starter-flyway instead of flyway-core. For more on designing the tables
themselves, see database design fundamentals.
Seeing it work
Start the app, hit the same endpoints from Part 9, and the behavior looks
identical — right up until you restart the app and the data is still
there, because it's no longer sitting in a List that dies with the JVM:
curl -X POST localhost:8080/api/tasks \
-H "Content-Type: application/json" \
-d '{"title": "Learn JPA", "dueDate": "2026-10-01"}'
# restart the app here
curl localhost:8080/api/tasks
# the task from before the restart is still there
That's the whole point of this part in one curl command.
What's next
The data now survives a restart, but the API still trusts every request blindly — send it a task with no title or a due date in 1990 and it'll happily save that too. Part 11: Validating Input and Handling Errors Like a Professional closes that gap: rejecting bad input at the boundary and returning error responses a client can actually use, instead of a stack trace or silently-saved garbage.