Chapter 08

Spring Data JPA

Spring Data writes your repository implementations from method names. That is genuinely excellent — right up until the generated SQL is not what you assumed. This chapter covers both halves.

⏱ 24 min readLevel: intermediateCore chapter

Setup

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>org.flywaydb</groupId>
  <artifactId>flyway-core</artifactId>
</dependency>
application.yml
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/bookstore
    username: bookstore_app
    password: ${DB_PASSWORD}
    hikari:
      maximum-pool-size: 20
      leak-detection-threshold: 20000

  jpa:
    open-in-view: false               # ← set this on day one, see below
    hibernate:
      ddl-auto: validate              # never "update" outside a toy project
    properties:
      hibernate:
        jdbc.batch_size: 50
        order_inserts: true
        order_updates: true
        query.fail_on_pagination_over_collection_fetch: true

  flyway:
    enabled: true                     # migrations own the schema
Two settings that are not optional

open-in-view: false — the default is true, which keeps a database connection open for the entire request including JSON serialisation. It hides LazyInitializationException and quietly exhausts your connection pool under load. Boot logs a warning about it at startup for good reason.

ddl-auto: validate — update lets Hibernate alter production schemas based on your entity classes. It cannot drop, cannot rename safely and has no review step. Use Flyway or Liquibase.

Entities

catalog/Book.java
package com.bitsnippets.bookstore.catalog;

import jakarta.persistence.*;

@Entity
@Table(name = "book",
       indexes = @Index(name = "idx_book_author", columnList = "author_id"))
public class Book {

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

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

    @Column(nullable = false, unique = true, length = 13)
    private String isbn;

    @Column(nullable = false, precision = 12, scale = 2)
    private BigDecimal price;

    @Enumerated(EnumType.STRING)                 // never ORDINAL
    @Column(nullable = false, length = 20)
    private BookStatus status = BookStatus.DRAFT;

    @ManyToOne(fetch = FetchType.LAZY)           // ALWAYS lazy on to-one
    @JoinColumn(name = "author_id", nullable = false)
    private Author author;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "book_category",
               joinColumns = @JoinColumn(name = "book_id"),
               inverseJoinColumns = @JoinColumn(name = "category_id"))
    private Set<Category> categories = new HashSet<>();

    @OneToMany(mappedBy = "book",
               cascade = CascadeType.ALL,
               orphanRemoval = true)
    private List<Review> reviews = new ArrayList<>();

    @Version
    private int version;                          // optimistic locking

    @CreatedDate
    @Column(updatable = false)
    private Instant createdAt;

    @LastModifiedDate
    private Instant updatedAt;

    protected Book() { }                          // JPA needs this; keep it protected

    public Book(String title, String isbn, BigDecimal price, Author author) {
        this.title = title;
        this.isbn = isbn;
        this.price = price;
        this.author = author;
    }

    /* keep both sides of the relationship consistent */
    public void addReview(Review review) {
        reviews.add(review);
        review.setBook(this);
    }

    public void removeReview(Review review) {
        reviews.remove(review);
        review.setBook(null);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Book other)) return false;
        return id != null && id.equals(other.id);
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();             // stable before and after persist
    }

    // getters, and setters only where mutation is legitimate
}
Do not use Lombok's @Data on entities

@Data generates equals, hashCode and toString over all fields. On an entity that means: touching every lazy association (N+1, or an exception), a hash code that changes when the id is assigned (breaking any HashSet the entity is already in), and infinite recursion through bidirectional relationships. Write the three methods by hand, based on the id, as above.

Fetch types

AssociationJPA defaultWhat you should use
@ManyToOneEAGERLAZY — always
@OneToOneEAGERLAZY — always
@OneToManyLAZYLAZY, fetch-joined where needed
@ManyToManyLAZYLAZY

The eager defaults on to-one associations are a historical mistake. Left alone, loading one Book can drag in the author, the publisher, the publisher's country and so on — every time, even when you only wanted the title.

Repositories

catalog/BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    /* ---- derived queries: the method name IS the query ---- */
    Optional<Book> findByIsbn(String isbn);

    List<Book> findByAuthorId(Long authorId);

    Page<Book> findByTitleContainingIgnoreCase(String fragment, Pageable pageable);

    List<Book> findByPriceBetweenAndStatus(BigDecimal min, BigDecimal max, BookStatus status);

    List<Book> findTop10ByOrderByCreatedAtDesc();

    boolean existsByIsbn(String isbn);

    long countByStatus(BookStatus status);

    void deleteByStatusAndCreatedAtBefore(BookStatus status, Instant cutoff);
}
KeywordGenerated predicate
And, Ora = ? AND b = ?
Betweenx BETWEEN ? AND ?
LessThan, GreaterThanEqualcomparisons
IsNull, IsNotNullnull checks
Like, Containing, StartingWithLIKE ? with wildcards added
IgnoreCaseLOWER(x) = LOWER(?)
In, NotInIN (?, ?, …)
OrderBy…Asc/DescORDER BY
Top, FirstLIMIT
DistinctSELECT DISTINCT
When the method name stops being readable, stop

findByAuthorNameAndCategoriesNameAndPriceBetweenOrderByPublishedOnDesc is a real thing people write. Past three conditions, switch to @Query or a Specification — the name is no longer documentation, it is an obstacle.

@Query

JPQL and native SQL
public interface BookRepository extends JpaRepository<Book, Long> {

    @Query("""
           SELECT b FROM Book b
           WHERE b.status = :status
             AND (:q IS NULL OR LOWER(b.title) LIKE LOWER(CONCAT('%', :q, '%')))
           """)
    Page<Book> search(@Param("status") BookStatus status,
                      @Param("q") String q,
                      Pageable pageable);

    /* fetch join: one query instead of N+1 */
    @Query("""
           SELECT DISTINCT b FROM Book b
           JOIN FETCH b.author
           LEFT JOIN FETCH b.categories
           WHERE b.id IN :ids
           """)
    List<Book> findAllWithDetails(@Param("ids") Collection<Long> ids);

    /* native SQL when you need vendor features */
    @Query(value = """
           SELECT b.* FROM book b
           WHERE to_tsvector('english', b.title) @@ plainto_tsquery('english', :q)
           """,
           countQuery = "SELECT count(*) FROM book b WHERE to_tsvector('english', b.title) @@ plainto_tsquery('english', :q)",
           nativeQuery = true)
    Page<Book> fullTextSearch(@Param("q") String q, Pageable pageable);

    /* bulk update — bypasses the persistence context, so clear it */
    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Query("UPDATE Book b SET b.status = :status WHERE b.author.id = :authorId")
    int updateStatusForAuthor(@Param("authorId") Long authorId,
                              @Param("status") BookStatus status);
}

Projections — do not load what you will not use

three flavours
/* 1 · interface projection — Spring generates the SELECT list */
public interface BookSummary {
    Long getId();
    String getTitle();
    BigDecimal getPrice();

    @Value("#{target.author.name}")     // careful: this loads the author
    String getAuthorName();
}

List<BookSummary> findByStatus(BookStatus status);

/* 2 · record (DTO) projection — explicit and efficient */
public record BookSummaryDto(Long id, String title, BigDecimal price, String authorName) { }

@Query("""
       SELECT new com.bitsnippets.bookstore.catalog.dto.BookSummaryDto(
              b.id, b.title, b.price, a.name)
       FROM Book b JOIN b.author a
       WHERE b.status = :status
       """)
List<BookSummaryDto> findSummaries(@Param("status") BookStatus status);

/* 3 · dynamic projection — one method, caller chooses the shape */
<T> List<T> findByStatus(BookStatus status, Class<T> type);

A list endpoint that needs four columns should select four columns. On a wide table with text and blob columns this is often a ten-fold difference.

The N+1 problem

The defining performance bug of JPA. You fetch a list, then touch a lazy association on each element, and each touch is a separate query.

The bug

List<Book> books = repo.findAll();      // 1 query

for (Book b : books) {
    b.getAuthor().getName();            // +1 query EACH
}
// 100 books → 101 queries

The fix

@EntityGraph(attributePaths = "author")
List<Book> findAll();

// or
@Query("SELECT b FROM Book b JOIN FETCH b.author")
List<Book> findAllWithAuthor();
// → 1 query
detecting it: make Hibernate count for you
logging:
  level:
    org.hibernate.SQL: DEBUG
    org.hibernate.stat: DEBUG

spring:
  jpa:
    properties:
      hibernate:
        generate_statistics: true      # logs query counts per session — dev only
Paging plus a collection fetch join is broken

JOIN FETCH on a @OneToMany combined with Pageable makes Hibernate fetch every row and paginate in memory — it logs "firstResult/maxResults specified with collection fetch; applying in memory" and then quietly eats your heap. Set hibernate.query.fail_on_pagination_over_collection_fetch=true to turn that warning into an exception, then page the ids first and fetch details for that page.

// step 1 — page the ids only
@Query("SELECT b.id FROM Book b WHERE b.status = :status")
Page<Long> findIdsByStatus(@Param("status") BookStatus status, Pageable pageable);

// step 2 — fetch the graph for exactly those ids
@Query("SELECT DISTINCT b FROM Book b JOIN FETCH b.categories WHERE b.id IN :ids")
List<Book> findAllWithCategories(@Param("ids") List<Long> ids);

Dynamic queries with Specifications

catalog/BookSpecifications.java
public final class BookSpecifications {

    public static Specification<Book> titleContains(String q) {
        return (root, query, cb) -> q == null || q.isBlank()
                ? null                                       // null = no predicate
                : cb.like(cb.lower(root.get("title")), "%" + q.toLowerCase() + "%");
    }

    public static Specification<Book> hasStatus(BookStatus status) {
        return (root, query, cb) -> status == null
                ? null
                : cb.equal(root.get("status"), status);
    }

    public static Specification<Book> priceBetween(BigDecimal min, BigDecimal max) {
        return (root, query, cb) -> {
            if (min == null && max == null) return null;
            if (min == null) return cb.lessThanOrEqualTo(root.get("price"), max);
            if (max == null) return cb.greaterThanOrEqualTo(root.get("price"), min);
            return cb.between(root.get("price"), min, max);
        };
    }
}
composing them
public interface BookRepository
        extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> { }

public Page<Book> search(BookSearchFilter filter, Pageable pageable) {
    Specification<Book> spec = Specification
            .where(titleContains(filter.q()))
            .and(hasStatus(filter.status()))
            .and(priceBetween(filter.minPrice(), filter.maxPrice()));

    return bookRepository.findAll(spec, pageable);
}

Type-safe and composable, but verbose. If your search screens are the heart of the product, compare this honestly against the MyBatis dynamic SQL approach — that is exactly the workload MyBatis was built for.

Auditing

common/JpaConfig.java
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class JpaConfig {

    @Bean
    AuditorAware<String> auditorProvider() {
        return () -> Optional.ofNullable(SecurityContextHolder.getContext())
                             .map(SecurityContext::getAuthentication)
                             .filter(Authentication::isAuthenticated)
                             .map(Authentication::getName);
    }
}

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {

    @CreatedDate  @Column(updatable = false) private Instant createdAt;
    @LastModifiedDate                        private Instant updatedAt;
    @CreatedBy    @Column(updatable = false) private String  createdBy;
    @LastModifiedBy                          private String  updatedBy;
}

JPA or MyBatis?

Both are first-class options in a Spring Boot application, and they coexist happily on one data source and inside one transaction.

WorkloadBetter fitWhy
CRUD over an object graph you ownJPADirty checking and cascades genuinely save work
Reporting, aggregations, window functionsMyBatisYou write the SQL you want, no translation layer
Legacy schema you cannot changeMyBatisResult maps absorb any column naming
Search screens with many optional filtersMyBatisDynamic SQL beats Specifications for readability
Bulk loadsMyBatis or plain JDBCBatch executor, no persistence context to flush
Stored proceduresMyBatisFirst-class support

Using both is a legitimate architecture, not a failure. If you go that way, the MyBatis course covers the second half in depth.

Checklist

  • open-in-view: false and ddl-auto: validate.
  • Every @ManyToOne and @OneToOne is LAZY.
  • equals/hashCode hand-written; no Lombok @Data on entities.
  • List endpoints use projections, not full entities.
  • Every list query has an entity graph or fetch join for what it will touch.
  • No Pageable combined with a collection fetch join.
  • Schema owned by Flyway, and the same migrations run in tests.
  • @Version on anything two users can edit at once.

Why is spring.jpa.open-in-view=true (the default) a problem?

Open Session In View keeps the EntityManager — and therefore a pooled connection — bound to the request thread until the response is written. It conveniently hides LazyInitializationException, which is precisely why N+1 queries during JSON serialisation go unnoticed until production load reveals the pool is exhausted.