TExcelTAD
Home › Spring Boot › Spring Data JPA Intro

Spring Data JPA Intro

Almost every API stores data in a relational database. In the Java world the standard way to map objects to tables is JPA (Jakarta Persistence), usually implemented by Hibernate. Spring Data JPA sits on top and removes the remaining boilerplate: you declare a repository interface, and Spring generates the implementation at startup.

The layers

text
Your service
   |  taskRepository.findByDoneFalse()
Spring Data JPA        generates repository implementations from interfaces
   |
JPA (jakarta.persistence)   standard API: EntityManager, @Entity, JPQL
   |
Hibernate 6.6          the JPA implementation: generates SQL, caches, tracks changes
   |
JDBC + HikariCP        connection pool, driver
   |
Database               H2, PostgreSQL, MySQL, ...
Term Meaning
Entity a class mapped to a table (@Entity)
EntityManager JPA's API to load, persist and query entities
Persistence context the set of entities currently managed; changes are tracked and flushed as SQL
Repository an interface for loading and saving one aggregate (e.g. TaskRepository)
JPQL an SQL-like query language over entities, not tables

Setup

xml
<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>

With H2 on the classpath and no spring.datasource.url, Boot creates an in-memory database and, because it is embedded, lets Hibernate create the tables from your entities (spring.jpa.hibernate.ddl-auto=create-drop). Perfect for learning; for real databases you will configure a URL and use migrations (see the Flyway lesson).

properties
# print every SQL statement Hibernate runs
spring.jpa.show-sql=true
# browser console for the H2 database at /h2-console
spring.h2.console.enabled=true

A first entity and repository

java
import jakarta.persistence.*;

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

    private String title;
    private boolean done;

    protected Task() {}                           // required by JPA
    public Task(String title) { this.title = title; }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public boolean isDone() { return done; }
    public void complete() { this.done = true; }
}

public interface TaskRepository extends JpaRepository<Task, Long> {
    List<Task> findByDoneFalse();                 // query derived from the method name
}

That interface is all you write. At startup Spring Data creates a proxy implementing save, findById, findAll, deleteById, count, and parses findByDoneFalse into a query.

java
@Bean
CommandLineRunner seed(TaskRepository repo) {
    return args -> {
        repo.save(new Task("Learn JPA"));
        repo.save(new Task("Write repository"));
        System.out.println("open tasks: " + repo.findByDoneFalse().size());
    };
}
bash · try it yourself
./mvnw -q spring-boot:run | grep -E "Hibernate|open tasks"
Hibernate: create table task (done boolean not null, id bigint generated by default as identity, title varchar(255), primary key (id))
Hibernate: insert into task (done,title,id) values (?,?,default)
Hibernate: insert into task (done,title,id) values (?,?,default)
Hibernate: select t1_0.id,t1_0.done,t1_0.title from task t1_0 where not(t1_0.done)
open tasks: 2

You can see everything Hibernate did: create the table from the entity, insert two rows, and translate findByDoneFalse into a where not(done) query.

The repository idea, in plain Java

A repository hides how data is stored behind a collection-like interface. Here is the same contract implemented with a HashMap — which is also how you can write fast unit tests for services without a database:

java · try it yourself
import java.util.*;

class Task {
    Long id;
    final String title;
    boolean done;
    Task(String title) { this.title = title; }
    public String toString() { return "Task{id=" + id + ", title='" + title + "', done=" + done + "}"; }
}

interface CrudRepository<T, ID> {
    T save(T entity);
    Optional<T> findById(ID id);
    List<T> findAll();
    long count();
    void deleteById(ID id);
}

class InMemoryTaskRepository implements CrudRepository<Task, Long> {
    private final Map<Long, Task> rows = new TreeMap<>();
    private long sequence = 0;

    public Task save(Task t) {
        if (t.id == null) t.id = ++sequence;   // like an IDENTITY column
        rows.put(t.id, t);
        return t;
    }
    public Optional<Task> findById(Long id) { return Optional.ofNullable(rows.get(id)); }
    public List<Task> findAll() { return new ArrayList<>(rows.values()); }
    public long count() { return rows.size(); }
    public void deleteById(Long id) { rows.remove(id); }

    List<Task> findByDoneFalse() { return rows.values().stream().filter(t -> !t.done).toList(); }
}

class Main {
    public static void main(String[] args) {
        InMemoryTaskRepository repo = new InMemoryTaskRepository();
        repo.save(new Task("Learn JPA"));
        Task second = repo.save(new Task("Write repository"));
        repo.save(new Task("Deploy"));

        second.done = true;
        repo.save(second);                     // id already set -> update
        System.out.println(repo.findAll());
        System.out.println("open: " + repo.findByDoneFalse().size() + " of " + repo.count());
        repo.deleteById(1L);
        System.out.println("after delete: " + repo.findById(1L).isPresent() + ", count " + repo.count());
    }
}
[Task{id=1, title='Learn JPA', done=false}, Task{id=2, title='Write repository', done=true}, Task{id=3, title='Deploy', done=false}]
open: 2 of 3
after delete: false, count 2

Spring Data's save follows the same rule: an entity without an id is inserted (persist), one with an id is merged (merge).

Repository interfaces

Interface Adds
Repository<T, ID> marker only — declare exactly the methods you want
CrudRepository<T, ID> save, findById, findAll, count, delete…
ListCrudRepository<T, ID> the same, returning List instead of Iterable
PagingAndSortingRepository<T, ID> findAll(Sort), findAll(Pageable)
JpaRepository<T, ID> all of the above + flush, saveAllAndFlush, batch deletes, getReferenceById

Tip: JpaRepository is the usual choice. If you want a narrow, read-only API, extend Repository and declare only findById and findAll.

Test yourself

What do you write to get a working Spring Data repository?

  1. A class implementing every CRUD method
  2. An interface extending e.g. JpaRepository<Task, Long>
  3. An XML mapping file
  4. SQL for each method

Which library actually generates the SQL in a default Spring Boot JPA setup?

  1. Spring MVC
  2. Jackson
  3. Hibernate
  4. HikariCP

What does repository.save(entity) do when the entity's id is null?

  1. Throws an exception
  2. Inserts a new row
  3. Updates all rows
  4. Does nothing