Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 66 ยท Data Access

Spring Data JPA Repositories

Use Spring Data JPA in Boot: entities, JpaRepository, derived queries from method names, @Query, projections, paging and sorting, and auditing.

Writing SQL by hand, as in the previous lesson, gives you full control. But a lot of data access is repetitive: save an object, find it by id, find all objects with a given author, count them. Spring Data JPA removes that repetition. You write an interface, describe the queries you need in the method names, and Spring creates the implementation at startup.

Underneath, it uses JPA (the Java persistence standard) with Hibernate as the engine, so you work with entities instead of rows. This lesson shows entities, repositories, derived queries, @Query, projections, paging and auditing in a Boot application. For the framework-level story, see Spring Data JPA, and for the entity basics behind it, Hibernate Setup and Entities.

The real Spring Data cannot run on this site, so its code is read-only. The main stand-in is a repository built from an interface with java.lang.reflect.Proxy: it reads the method name, writes SQL, and runs it on real H2. That is, in miniature, how Spring Data works too.

Entities and repositories

An entity is a class mapped to a table. A repository is an interface that gives you data operations for one entity type.

Java
@Entity
@Table(name = "books")
class Book {

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

    @Column(nullable = false, length = 100)
    private String title;

    @Column(nullable = false, length = 60)
    private String author;

    private int pages;

    protected Book() { }                       // required by JPA

    Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }

    // getters (and setters only for what may change)
}

interface BookRepository extends JpaRepository<Book, Long> {
}

The jakarta imports (jakarta.persistence.*) apply to Boot 3 and 4; the older javax.persistence is gone. Extending JpaRepository<Book, Long> (entity type, id type) gives you, with no code:

  • save(book): insert when the entity is new, update when it exists.
  • findById(id): returns an Optional<Book>.
  • findAll(), findAll(Sort), findAll(Pageable).
  • existsById, count, deleteById, delete, saveAll.

Boot finds repository interfaces on its own (no @EnableJpaRepositories needed when they live under your main application package) and registers each as a bean you can inject by constructor.

What you write, what Spring writes

An interface Methods describe what you need.
A proxy Spring builds the class at startup.
The query Created from the method name.
Entities Rows come back as objects.
1 / 2

Mapping annotations in detail

Without extra annotations, JPA maps a class Book to a table book and each field to a column of the same name (Boot's naming strategy turns publishedYear into published_year). These annotations change that.

@Table names the table and declares table-level rules:

Java
@Entity
@Table(
    name = "books",
    schema = "catalog",                                           // optional
    uniqueConstraints = @UniqueConstraint(name = "uk_books_isbn", columnNames = "isbn"),
    indexes = {
        @Index(name = "idx_books_author", columnList = "author"),
        @Index(name = "idx_books_author_year", columnList = "author, published_year")
    })
class Book { /* ... */ }

uniqueConstraints can span several columns (columnNames = {"author", "title"}), which a single-column @Column(unique = true) cannot. These declarations only create anything when Hibernate generates the schema (ddl-auto, tests); with Flyway you write the same constraint and index in SQL, and the annotation documents it. The database enforces the rule either way, and a violation reaches your code as a DataIntegrityViolationException.

@Id marks the primary key; every entity needs exactly one (or a composite key with @EmbeddedId/@IdClass). @GeneratedValue says who creates the value:

Strategy Meaning Use when
IDENTITY the database assigns it (auto-increment, identity column) MySQL, SQL Server, simple schemas; disables JDBC insert batching
SEQUENCE the id comes from a database sequence, often fetched in blocks PostgreSQL, Oracle, H2; best for batch inserts
UUID the application generates a UUID ids created before the insert, or exposed in URLs
AUTO Hibernate picks a strategy for the dialect quick demos; be explicit in real code
none you assign the id yourself (natural keys) codes such as a country code

@Column controls one column: name, nullable, length, unique, precision/scale for decimals, updatable = false for values that must never change after insert, and columnDefinition for raw DDL. Mark fields that are not stored with @Transient, enum fields with @Enumerated(EnumType.STRING) (never the default ORDINAL, which breaks when you reorder the enum), and dates with LocalDate/Instant instead of the legacy java.util.Date.

To see the generated SQL while you experiment, set spring.jpa.show-sql=true (prints plain SQL to the console) or, better, logging.level.org.hibernate.SQL=debug with logging.level.org.hibernate.orm.jdbc.bind=trace for the bound parameter values, and add spring.jpa.properties.hibernate.format_sql=true to indent it. The TryIt runs a table shaped like the one above on real H2 so you can watch the unique constraint and the generated ids at work; plain JDBC stands in for Hibernate here.

Java Unique constraint, index and generated ids on H2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Derived queries

The magic part: a method named findByAuthor becomes select ... where author = ?. Spring Data parses the name into a subject (find, count, exists, delete) and a predicate built from property names and keywords.

Java
interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthor(String author);
    List<Book> findByAuthorAndPagesLessThan(String author, int pages);
    List<Book> findByTitleContainingIgnoreCase(String fragment);
    List<Book> findByPagesBetweenOrderByTitleAsc(int from, int to);
    Optional<Book> findFirstByAuthorOrderByPagesDesc(String author);
    List<Book> findTop3ByOrderByPagesDesc();
    long countByAuthor(String author);
    boolean existsByTitle(String title);
    void deleteByAuthor(String author);
}

Common keywords: And, Or, Is/Equals, Not, LessThan, GreaterThan, Between, Like, Containing, StartingWith, In, IsNull, True, IgnoreCase, OrderBy...Asc/Desc, First/Top, Distinct. If a property name is wrong, the application fails at startup with an error naming it, which is a real strength: typos do not wait for production.

Name-derived queries are good for two or three conditions. A method called findByAuthorAndPagesGreaterThanAndTitleContainingIgnoreCaseOrderByTitleAsc is a sign to write the query yourself.

The runnable stand-in below builds a repository for this very kind of interface using Proxy. It splits the method name, builds SQL, prints it, and runs it on H2.

Java A repository proxy built from method names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The printed SQL shows what a derived query turns into. Spring Data does the same job with a much richer parser, builds a JPA criteria query instead of text, and checks the property names against the entity metamodel at startup.

Your own query with @Query

When the name gets unwieldy, or you need a join, an aggregate or a hand-tuned statement, write the query:

Java
interface BookRepository extends JpaRepository<Book, Long> {

    @Query("select b from Book b where b.author = :author and b.pages > :minPages order by b.title")
    List<Book> longBooksBy(@Param("author") String author, @Param("minPages") int minPages);

    @Query(value = "select * from books where lower(title) like lower(concat('%', :q, '%'))",
           nativeQuery = true)
    List<Book> searchNative(@Param("q") String q);

    @Modifying
    @Query("update Book b set b.pages = b.pages + 1 where b.author = :author")
    int growBooksBy(@Param("author") String author);
}
  • The default language is JPQL: you query entities and their fields (Book b, b.author), not tables and columns.
  • nativeQuery = true sends plain SQL. Use it sparingly; it ties you to one database.
  • Bind values with :name parameters. Do not glue strings together, as with raw JDBC.
  • @Modifying marks an update or delete. These bulk statements bypass the entity cache, so objects already loaded in the same transaction may be stale afterwards.

Projections

Loading a full entity to show two columns wastes memory and time. A projection returns only what you need. The simplest form is a record (a DTO projection):

Java
record BookSummary(String title, String author) {}

interface BookRepository extends JpaRepository<Book, Long> {
    List<BookSummary> findByAuthor(String author);              // selects only title and author
    <T> List<T> findByPagesGreaterThan(int pages, Class<T> type);   // caller picks the shape
}

Interface-based projections (an interface with getters such as String getTitle()) work too. In both cases Spring Data narrows the SELECT to the listed properties. Besides saving data, projections also keep entities out of your API responses, which fits the advice in Request and Response Bodies with Jackson.

Paging and sorting

Never return an unbounded list from a web endpoint. Accept a Pageable and return a Page:

Java
interface BookRepository extends JpaRepository<Book, Long> {
    Page<Book> findByAuthor(String author, Pageable pageable);
}

@GetMapping("/books")
Page<BookSummary> list(@RequestParam String author,
                       @PageableDefault(size = 20, sort = "title") Pageable pageable) {
    return repo.findByAuthor(author, pageable).map(b -> new BookSummary(b.getTitle(), b.getAuthor()));
}

In a controller, Boot resolves Pageable from ?page=0&size=20&sort=title,desc. A Page carries the content plus totalElements and totalPages, which costs an extra count query. If you only need "is there a next page", use Slice, which skips the count. Cap the maximum page size (spring.data.web.pageable.max-page-size, default 2000, so lower it) so that a client cannot ask for a million rows. Spring Data checks the sort property against the entity, and rejects names it does not know; this matters because a sort value reaches the query text.

The second stand-in shows the paging arithmetic and the sort whitelist on real H2: a count query, a limit/offset query, and a record projection that selects only two columns.

Java Paging, sorting and a projection on H2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Page 2 holds a single book because five items do not divide by two. The hostile sort name is refused before it can reach any SQL.

Auditing

Most business tables want to know when a row was created and changed, and by whom. Spring Data fills those columns for you:

Java
@Configuration
@EnableJpaAuditing
class AuditConfig {
    @Bean
    AuditorAware<String> auditor() {
        return () -> Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
            .map(Authentication::getName);
    }
}

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
abstract class Auditable {
    @CreatedDate     private Instant createdAt;
    @LastModifiedDate private Instant updatedAt;
    @CreatedBy       private String createdBy;
}

@Entity
class Book extends Auditable { /* ... */ }

Store timestamps as Instant (UTC) and convert for display. The AuditorAware bean answers "who is the current user"; here it reads Spring Security, which you will meet in Spring Security Fundamentals.

Settings worth knowing

YAML
spring:
  jpa:
    hibernate:
      ddl-auto: validate      # never "update" or "create" outside experiments
    open-in-view: false       # see the transactions lesson
    properties:
      hibernate:
        jdbc:
          batch_size: 50

ddl-auto: validate checks that the schema matches your entities and fails fast if not; let a migration tool such as Flyway change the schema. Add logging.level.org.hibernate.SQL=debug while developing to see every statement, because watching the SQL is the best protection against surprises, as the next lesson shows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Who provides the implementation of a Spring Data repository interface?

    Spring Data inspects the interface and registers a proxy that implements it. Derived queries are parsed from method names during startup.
  2. 2. What happens at startup if a derived query method refers to a property the entity does not have?

    Derived queries are validated when the repository is created, so a typo in a method name stops the application immediately instead of failing in production.
  3. 3. When is a @Query method better than a derived query?

    Derived queries are great for simple filters. Long names are hard to read, and joins or aggregates are easier to express in JPQL or SQL.
  4. 4. Why return a projection (such as a record) instead of an entity from a list endpoint?

    A projection narrows the SELECT and exposes only the fields you choose, saving memory and avoiding leaks of internal columns.
  5. 5. What is the cost of returning a Page compared with a Slice?

    Page includes totalElements and totalPages, which needs a count query. Slice only knows whether another page exists.

Summary

  • Spring Data JPA turns a repository interface into a working bean; entities map to tables and JpaRepository gives you CRUD, paging and sorting.
  • Derived queries come from method names and are validated at startup; use @Query (JPQL or native) when names get long or you need joins.
  • Bind values with named parameters; mark updates and deletes with @Modifying and remember they bypass the entity cache.
  • Projections (records or interfaces) load only the columns you need and keep entities out of responses.
  • Accept a Pageable, cap the page size, and prefer Slice when you do not need totals.
  • Auditing annotations fill created and modified columns; set ddl-auto: validate and manage the schema with migrations.

Next: Entity Relationships and the N+1 Problem.