Java NotesRohit’s interview study guide
Chapter 14

Data Access with Spring Data JPA

How a Spring Boot service talks to a relational database: JPA and Hibernate underneath, Spring Data repositories on top, the N+1 problem and lazy loading shown in the real SQL log, what @Transactional really rolls back, schema migrations with Flyway, and plain SQL with JdbcClient. Every example was run with Spring Boot 4.2.0 (Hibernate ORM 7.4.15, Spring Data JPA 4.2) on Java 25, against the H2 in-memory database that the starter includes.

Try it yourself. Every example is the starter project from chapter 11 plus the files shown. Most are runner apps like the ones in chapter 12: their application.properties starts with the same four lines (no web server, no banner, warnings only) and they run with ./mvnw -q spring-boot:run. Several add spring.jpa.show-sql=true, which makes Hibernate print every SQL statement it sends, prefixed with Hibernate:. That log is the most useful thing in this chapter: JPA writes SQL for you, and you only understand JPA once you watch the SQL it writes.

9 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#JPA, Hibernate and Spring Data

Added

Three names show up together in every Java job ad, and they're three layers of one stack:

LayerWhat it isClosest thing in Node.js
JPA (Jakarta Persistence 3.2)a specification: the @Entity, @Id, @OneToMany annotations and the EntityManager API. Interfaces, no SQL engineno real equivalent: a standard API that several ORMs implement
Hibernate ORM (7.4 in Boot 4.2)the implementation: maps objects to tables, generates SQL, tracks changesthe engine inside TypeORM or Prisma
Spring Data JPA (4.2)repositories on top: you declare an interface, Spring generates the implementationa TypeORM Repository, or Prisma's generated client methods

When you last wrote Java, this was javax.persistence and maybe a hand-written Hibernate DAO with session.beginTransaction(). Two things changed: the package is now jakarta.persistence (Java EE moved to the Eclipse Foundation and was renamed Jakarta EE; Spring Boot 3 and later use the new names), and almost nobody writes DAOs by hand any more, because Spring Data generates them.

The idea that surprises Node.js developers most is the persistence context. With Prisma, every call is a query and every change is an explicit update. JPA works differently: inside a transaction, Hibernate keeps a map of every entity it has loaded, keyed by type and id. Think of it as a working copy of the rows you touched:

  • ask for the same row twice and you get the same Java object back, with no second query (the first-level cache);
  • change a field on a loaded entity and you don't call save: at commit, Hibernate compares each entity with a snapshot taken when it was loaded (dirty checking) and writes an UPDATE for what changed;
  • SQL is sent when Hibernate flushes the working copy, normally just before commit, not at the line where you changed the field.

The working copy lives as long as the transaction. When it ends, the entities become detached: plain objects that Hibernate no longer watches. Much of this chapter (lazy loading, LazyInitializationException, open-in-view) follows from that one fact.

src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private long priceCents;

    protected Product() {
    }

    public Product(String name, long priceCents) {
        this.name = name;
        this.priceCents = priceCents;
    }

    public Long getId() {
        return id;
    }

    public void setPriceCents(long priceCents) {
        this.priceCents = priceCents;
    }
}
src/main/java/com/example/shop/PriceDemo.java
package com.example.shop;

import jakarta.persistence.EntityManager;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
class PriceService {
    private final EntityManager em;

    PriceService(EntityManager em) {
        this.em = em;
    }

    @Transactional
    public Long create() {
        Product keyboard = new Product("Keyboard", 4999);
        em.persist(keyboard);
        return keyboard.getId();
    }

    @Transactional
    public void raisePrice(Long id) {
        Product first = em.find(Product.class, id);
        Product second = em.find(Product.class, id);
        System.out.println("same object? " + (first == second));
        first.setPriceCents(5499);
        System.out.println("end of raisePrice, no save called");
    }
}

@Component
class PriceDemo implements CommandLineRunner {
    private final PriceService prices;

    PriceDemo(PriceService prices) {
        this.prices = prices;
    }

    @Override
    public void run(String... args) {
        Long id = prices.create();
        prices.raisePrice(id);
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.show-sql=true
Terminal
$ ./mvnw -q spring-boot:run
Hibernate: drop table if exists product cascade 
Hibernate: create table product (id bigint generated by default as identity, price_cents bigint not null, name varchar(255), primary key (id))
Hibernate: insert into product (name,price_cents,id) values (?,?,default)
Hibernate: select p1_0.id,p1_0.name,p1_0.price_cents from product p1_0 where p1_0.id=?
same object? true
end of raisePrice, no save called
Hibernate: update product set name=?,price_cents=? where id=?
Hibernate: drop table if exists product cascade
What’s happening
  1. @Entity maps Product to a table called product; @Id marks the primary key, and IDENTITY lets the database generate it. At startup Hibernate prints the DDL it runs: it drops and creates the table from the class (price_cents bigint not null, because a long can't be null). Boot does that by default only for embedded databases like H2 (Schema migrations with Flyway covers real ones).
  2. create() runs in a transaction (the @Transactional proxy from chapter 12). em.persist makes the new object managed, and because the id comes from the database, Hibernate sends the insert straight away. The transaction commits and the working copy is thrown away.
  3. raisePrice starts a new transaction with an empty working copy. The first em.find runs the one select you see. The second em.find for the same id runs no query: it returns the object already in the persistence context, so same object? true.
  4. setPriceCents(5499) just changes a field in memory, and the method ends without calling any save method: end of raisePrice, no save called is printed before any SQL.
  5. Then the proxy commits. Before committing, Hibernate flushes: it compares first with its snapshot, sees the price changed, and sends update product set name=?,price_cents=? where id=?. That's dirty checking.
  6. At shutdown the H2 table is dropped again (drop table if exists product cascade). The lesson: in JPA, SQL happens at flush time, not where your Java line is, and a managed entity is saved simply by being changed inside a transaction.
AdvancedGotcha: dirty checking saves unintended changes

#Entities and repositories

Added

An entity is a class whose instances are rows. The rules are short: annotate it @Entity, give it an @Id, and give it a no-argument constructor (it can be protected; Hibernate uses it to create objects when reading rows). The class must not be final, because Hibernate subclasses entities to make lazy proxies (the same trick as Spring's proxies). Field names become column names in snake case: priceCents is the column price_cents.

A repository is the object you load and save entities through. In Spring Data you write only an interface that extends JpaRepository<Product, Long> (entity type, id type). At startup Spring creates a proxy that implements it, with these methods ready to use:

MethodWhat it does
save(entity) / saveAll(list)insert a new entity, or merge a detached one; returns the managed entity (with its generated id)
findById(id)Optional<Product>, empty when there's no such row
findAll() / findAll(Sort) / findAll(Pageable)everything, sorted, or one page
count() / existsById(id)select count(…)
deleteById(id) / delete(entity)delete one

It's the same idea as a TypeORM Repository<Product> or prisma.product, but you never write the class: the interface is the whole repository.

src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private long priceCents;

    protected Product() {
    }

    public Product(String name, long priceCents) {
        this.name = name;
        this.priceCents = priceCents;
    }

    public Long getId() {
        return id;
    }

    public void setPriceCents(long priceCents) {
        this.priceCents = priceCents;
    }

    @Override
    public String toString() {
        return name + " (" + priceCents + ")";
    }
}
src/main/java/com/example/shop/ProductRepository.java
package com.example.shop;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
}
src/main/java/com/example/shop/CrudDemo.java
package com.example.shop;

import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

@Component
class CrudDemo implements CommandLineRunner {
    private final ProductRepository products;

    CrudDemo(ProductRepository products) {
        this.products = products;
    }

    @Override
    public void run(String... args) {
        products.saveAll(List.of(
                new Product("Mechanical keyboard", 8999),
                new Product("Wireless mouse", 2999),
                new Product("27-inch monitor", 29999)));
        System.out.println("count: " + products.count());

        Product mouse = products.findById(2L).orElseThrow();
        System.out.println("found: " + mouse);
        System.out.println("id 99: " + products.findById(99L));

        mouse.setPriceCents(2499);
        products.save(mouse);
        System.out.println("by price: " + products.findAll(Sort.by("priceCents")));

        products.deleteById(3L);
        Product trackball = products.save(new Product("Trackball", 5999));
        System.out.println("exists 3? " + products.existsById(3L) + ", new id: " + trackball.getId() + ", count: " + products.count());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
count: 3
found: Wireless mouse (2999)
id 99: Optional.empty
by price: [Wireless mouse (2499), Mechanical keyboard (8999), 27-inch monitor (29999)]
exists 3? false, new id: 4, count: 3
What’s happening
  1. ProductRepository has no body at all. At startup Spring Data finds it (it's under com.example.shop, like any component), creates an implementation, and registers it as a bean; CrudDemo gets it by constructor injection.
  2. saveAll inserts three rows. The ids come from the database's identity column, so they're 1, 2 and 3, and count() says count: 3.
  3. findById(2L) returns an Optional holding the mouse; for id 99 it's Optional.empty, not null and not an exception. That's chapter 05's "Optional for return values" rule applied by the library.
  4. mouse was loaded in the transaction of findById, which has ended, so it's detached: changing its price does nothing by itself. save(mouse) merges it back and writes the UPDATE, so the sorted list shows Wireless mouse (2499) first. Each repository method has its own short transaction, which is why save is needed here and wasn't inside raisePrice above.
  5. deleteById(3L) removes the monitor. The new trackball gets id 4, not 3: identity columns never reuse a value. exists 3? false, new id: 4, count: 3.
AdvancedNote: repository methods are transactional
AdvancedTip: IDENTITY or SEQUENCE ids
AdvancedGotcha: entity equals, hashCode and records

#Derived queries, @Query and pagination

Added

Spring Data can write a query from a method name. findByCategoryOrderByPriceCentsDesc(String category) is parsed into parts: find…By (a select), Category (a property of the entity), OrderByPriceCentsDesc. Keywords such as And, Or, LessThan, Between, Containing, IgnoreCase, Top3 and countBy/existsBy/deleteBy cover most everyday lookups. Because the names refer to entity properties, a typo fails at startup, not at the first call.

When a name would get silly, write the query yourself with @Query. By default it's JPQL: SQL-like, but over entities and fields (from Product p where p.priceCents …), so it survives column renames and database changes. With nativeQuery = true it's raw SQL for your database, for features JPQL doesn't have.

Pagination is built in: add a Pageable parameter and return Page<T>. Spring adds offset/limit and runs a second count query so the page knows the total. In Node terms, it's the skip/take plus count() you'd write by hand with Prisma, done for you.

src/main/resources/schema.sql
create table product (
    id bigint primary key,
    name varchar(100) not null,
    category varchar(50) not null,
    price_cents bigint not null
);
src/main/resources/data.sql
insert into product values
    (1, 'Mechanical keyboard', 'keyboards', 8999),
    (2, 'Compact keyboard', 'keyboards', 4999),
    (3, 'Wireless mouse', 'mice', 2999),
    (4, 'Trackball', 'mice', 5999),
    (5, 'Gaming mouse', 'mice', 6999),
    (6, '27-inch monitor', 'monitors', 29999);
src/main/java/com/example/shop/Products.java
package com.example.shop;

import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

@Entity
class Product {
    @Id
    private Long id;
    private String name;
    private String category;
    private long priceCents;

    @Override
    public String toString() {
        return name + " (" + priceCents + ")";
    }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByCategoryOrderByPriceCentsDesc(String category);

    List<Product> findByNameContainingIgnoreCase(String text);

    long countByPriceCentsLessThan(long cents);

    @Query("select p from Product p where p.priceCents between :min and :max order by p.priceCents")
    List<Product> inPriceRange(@Param("min") long min, @Param("max") long max);

    @Query(value = "select * from product order by price_cents desc limit 1", nativeQuery = true)
    Product mostExpensive();

    Page<Product> findByCategory(String category, Pageable pageable);
}
src/main/java/com/example/shop/QueryDemo.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

@Component
class QueryDemo implements CommandLineRunner {
    private final ProductRepository products;

    QueryDemo(ProductRepository products) {
        this.products = products;
    }

    @Override
    public void run(String... args) {
        System.out.println(products.findByCategoryOrderByPriceCentsDesc("mice"));
        System.out.println(products.findByNameContainingIgnoreCase("KEYBOARD"));
        System.out.println(products.countByPriceCentsLessThan(5000));
        System.out.println(products.inPriceRange(5000, 9000));
        System.out.println(products.mostExpensive());
        Page<Product> page = products.findByCategory("mice", PageRequest.of(0, 2, Sort.by("priceCents")));
        System.out.println(page.getContent() + " page " + (page.getNumber() + 1) + " of "
                + page.getTotalPages() + ", " + page.getTotalElements() + " in all");
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
Terminal
$ ./mvnw -q spring-boot:run
Hibernate: select p1_0.id,p1_0.category,p1_0.name,p1_0.price_cents from product p1_0 where p1_0.category=? order by p1_0.price_cents desc
[Gaming mouse (6999), Trackball (5999), Wireless mouse (2999)]
Hibernate: select p1_0.id,p1_0.category,p1_0.name,p1_0.price_cents from product p1_0 where upper(p1_0.name) like upper(?) escape '\'
[Mechanical keyboard (8999), Compact keyboard (4999)]
Hibernate: select count(p1_0.id) from product p1_0 where p1_0.price_cents<?
2
Hibernate: select p1_0.id,p1_0.category,p1_0.name,p1_0.price_cents from product p1_0 where p1_0.price_cents between ? and ? order by p1_0.price_cents
[Trackball (5999), Gaming mouse (6999), Mechanical keyboard (8999)]
Hibernate: select * from product order by price_cents desc limit 1
27-inch monitor (29999)
Hibernate: select p1_0.id,p1_0.category,p1_0.name,p1_0.price_cents from product p1_0 where p1_0.category=? order by p1_0.price_cents fetch first ? rows only
Hibernate: select count(p1_0.id) from product p1_0 where p1_0.category=?
[Wireless mouse (2999), Trackball (5999)] page 1 of 2, 3 in all
What’s happening
  1. The data comes from two plain SQL files: Boot runs schema.sql and then data.sql at startup for an embedded database. ddl-auto=none tells Hibernate not to create tables itself, so the SQL log below holds only the queries the repository runs.
  2. findByCategoryOrderByPriceCentsDesc("mice") becomes where p1_0.category=? order by p1_0.price_cents desc: three mice, most expensive first. The ? is a bind parameter; derived queries are never built by string concatenation, so they're safe from SQL injection.
  3. findByNameContainingIgnoreCase("KEYBOARD") becomes upper(p1_0.name) like upper(?) (Spring wraps the value in %…%), so both keyboards match. countByPriceCentsLessThan(5000) becomes a select count(…) and returns 2 (the compact keyboard and the wireless mouse).
  4. The JPQL @Query names the entity and field (Product p, p.priceCents); Hibernate translates them to product and price_cents. The native query is sent exactly as written, limit 1 and all, and returns the monitor.
  5. PageRequest.of(0, 2, Sort.by("priceCents")) asks for the first page (pages count from 0) of size 2. Hibernate runs the page query with fetch first ? rows only (H2's way of writing limit), then a second query, select count(…), to learn there are 3 mice in all. So: two cheapest mice, page 1 of 2, 3 in all.
AdvancedTip: Slice skips the count query
AdvancedGotcha: deep offset pages are slow
AdvancedA typo in a derived query fails at startup

Typos in derived query names fail fast. Here the method says Nme instead of Name:

src/main/java/com/example/shop/Products.java
package com.example.shop;

import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;

@Entity
class Product {
    @Id
    private Long id;
    private String name;
}

interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByNme(String name);
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run 2>&1 | grep -o "Cannot create query.*" | head -1
Cannot create query for method [ProductRepository.findByNme(java.lang.String)]; No property 'nme' found for type 'Product'; Did you mean 'name'
What’s happening
  1. The full output is a long stack trace, so the command keeps only the interesting line: grep -o prints the part of the line from Cannot create query onwards, and head -1 keeps the first match.
  2. Spring Data parses the method name while creating the repository bean, finds no property nme on Product, and refuses: No property 'nme' found for type 'Product'; Did you mean 'name'.
  3. Because the repository bean can't be created, the whole application fails to start. You find the typo on your machine or in the CI test that starts the context, never in production at the first call.

#Relationships and the N+1 problem

Added

Entities can point at each other. A product belongs to one category, so Product has a @ManyToOne Category category (the foreign key category_id lives in the product table). A category has many products, so Category can have a @OneToMany(mappedBy = "category") List<Product> products; mappedBy says "the foreign key is owned by Product.category, don't make another one".

Each relationship has a fetch type. LAZY means "don't load the other side until someone touches it": Hibernate puts a placeholder there (a proxy object, or an uninitialised collection) and runs a query when you first use it. EAGER means "always load it with the entity". The JPA defaults are a trap worth knowing for interviews: @OneToMany and @ManyToMany default to LAZY, but @ManyToOne and @OneToOne default to EAGER.

Lazy loading is what makes the N+1 problem possible: one query loads a list of N categories, and then a loop touches each category's products, so Hibernate runs one more query per category. With 3 categories that's 4 queries; with 500 it's 501, each a network round trip. Nothing fails, the page is just slow, and the code looks innocent. The same thing happens in Node with any ORM that lazy-loads, or with a GraphQL resolver per row (where DataLoader is the usual fix).

The fixes all say the same thing: tell Hibernate up front what you'll need, so it loads it in the same query. A JPQL fetch join (join fetch c.products) or Spring Data's @EntityGraph(attributePaths = "products") both turn it into one query with a join.

src/main/resources/schema.sql
create table category (id bigint primary key, name varchar(50) not null);
create table product (
    id bigint primary key,
    name varchar(100) not null,
    price_cents bigint not null,
    category_id bigint not null references category (id)
);
src/main/resources/data.sql
insert into category values (1, 'Keyboards'), (2, 'Mice'), (3, 'Monitors');
insert into product values
    (1, 'Mechanical keyboard', 8999, 1), (2, 'Compact keyboard', 4999, 1),
    (3, 'Wireless mouse', 2999, 2), (4, 'Trackball', 5999, 2),
    (5, '27-inch monitor', 29999, 3), (6, '32-inch monitor', 44999, 3);
src/main/java/com/example/shop/Catalog.java
package com.example.shop;

import java.util.ArrayList;
import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

@Entity
class Category {
    @Id
    private Long id;
    private String name;

    @OneToMany(mappedBy = "category")
    private List<Product> products = new ArrayList<>();

    String getName() {
        return name;
    }

    List<Product> getProducts() {
        return products;
    }
}

@Entity
class Product {
    @Id
    private Long id;
    private String name;
    private long priceCents;

    @ManyToOne(fetch = FetchType.LAZY)
    private Category category;
}

interface CategoryRepository extends JpaRepository<Category, Long> {
    @EntityGraph(attributePaths = "products")
    @Query("select c from Category c")
    List<Category> findAllWithProducts();

    @Query("select c from Category c join fetch c.products")
    List<Category> findAllJoinFetch();
}
src/main/java/com/example/shop/Report.java
package com.example.shop;

import java.util.List;

import jakarta.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
class Report {
    private final CategoryRepository categories;

    Report(CategoryRepository categories) {
        this.categories = categories;
    }

    @Transactional(readOnly = true)
    public void print(String how) {
        List<Category> list = switch (how) {
            case "findAll" -> categories.findAll();
            case "entity graph" -> categories.findAllWithProducts();
            default -> categories.findAllJoinFetch();
        };
        for (Category c : list) {
            System.out.println(c.getName() + ": " + c.getProducts().size() + " products");
        }
    }
}

@Component
class ReportDemo implements CommandLineRunner {
    private final Report report;
    private final Statistics stats;

    ReportDemo(Report report, EntityManagerFactory emf) {
        this.report = report;
        this.stats = emf.unwrap(SessionFactory.class).getStatistics();
    }

    @Override
    public void run(String... args) {
        for (String how : List.of("findAll", "entity graph", "join fetch")) {
            System.out.println("--- " + how);
            stats.clear();
            report.print(how);
            System.out.println("queries: " + stats.getPrepareStatementCount());
        }
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.generate_statistics=true
Terminal
$ ./mvnw -q spring-boot:run
--- findAll
Hibernate: select c1_0.id,c1_0.name from category c1_0
Hibernate: select p1_0.category_id,p1_0.id,p1_0.name,p1_0.price_cents from product p1_0 where p1_0.category_id=?
Keyboards: 2 products
Hibernate: select p1_0.category_id,p1_0.id,p1_0.name,p1_0.price_cents from product p1_0 where p1_0.category_id=?
Mice: 2 products
Hibernate: select p1_0.category_id,p1_0.id,p1_0.name,p1_0.price_cents from product p1_0 where p1_0.category_id=?
Monitors: 2 products
queries: 4
--- entity graph
Hibernate: select c1_0.id,c1_0.name,p1_0.category_id,p1_0.id,p1_0.name,p1_0.price_cents from category c1_0 left join product p1_0 on c1_0.id=p1_0.category_id
Keyboards: 2 products
Mice: 2 products
Monitors: 2 products
queries: 1
--- join fetch
Hibernate: select c1_0.id,c1_0.name,p1_0.category_id,p1_0.id,p1_0.name,p1_0.price_cents from category c1_0 join product p1_0 on c1_0.id=p1_0.category_id
Keyboards: 2 products
Mice: 2 products
Monitors: 2 products
queries: 1
What’s happening
  1. Three categories with two products each. Report.print runs in a read-only transaction, so lazy loading can work inside it; it loads the categories one of three ways and prints each one's product count. hibernate.generate_statistics=true turns on Hibernate's counters, and getPrepareStatementCount() counts the SQL statements since stats.clear(): a number you can assert on, unlike a log.
  2. findAll: one select … from category. Each category's products list is an uninitialised lazy collection. The loop calls getProducts().size() on Keyboards, and only then Hibernate runs select … from product … where p1_0.category_id=?. Look at the order in the log: each product query appears just before the line that needed it.
  3. That repeats for Mice and Monitors: queries: 4, which is 1 query for the list plus N = 3 for the products. That's the N+1 problem, and it grows with the data, not with the code.
  4. @EntityGraph(attributePaths = "products") on a repository method tells Hibernate to load products together with the categories. One select with a left join product: queries: 1, same output.
  5. join fetch in JPQL does the same with an inner join: queries: 1. Hibernate 6 and later remove the duplicate categories the join produces by themselves (each category appears once per product in the SQL result), so the old select distinct advice is no longer needed.
  6. The difference between the two fixes is in the SQL: the entity graph used a left join, so a category with no products would still be listed; the fetch join is an inner join, so it would drop that category. Choose the entity graph when "with no children" rows must stay.
AdvancedGotcha: MultipleBagFetchException
AdvancedFetch joins and pagination

A classic interview warning: a collection fetch join and a page limit don't mix in plain SQL, because limit 2 would cut rows of the join (category–product pairs), not categories. Older Hibernate versions therefore loaded every row and paged in memory, logging firstResult/maxResults specified with collection fetch; applying in memory, which on a big table is worse than the N+1. Hibernate 7.4, the version Boot 4.2 uses, handles it differently, as its SQL shows:

src/main/resources/schema.sql
create table category (id bigint primary key, name varchar(50) not null);
create table product (
    id bigint primary key,
    name varchar(100) not null,
    category_id bigint not null references category (id)
);
src/main/resources/data.sql
insert into category values (1, 'Keyboards'), (2, 'Mice'), (3, 'Monitors');
insert into product values
    (1, 'Mechanical keyboard', 1), (2, 'Compact keyboard', 1),
    (3, 'Wireless mouse', 2), (4, 'Trackball', 2),
    (5, '27-inch monitor', 3), (6, '32-inch monitor', 3);
src/main/java/com/example/shop/Catalog.java
package com.example.shop;

import java.util.ArrayList;
import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Entity
class Category {
    @Id
    private Long id;
    private String name;

    @OneToMany(mappedBy = "category")
    private List<Product> products = new ArrayList<>();

    String getName() {
        return name;
    }

    List<Product> getProducts() {
        return products;
    }
}

@Entity
class Product {
    @Id
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private Category category;
}

interface CategoryRepository extends JpaRepository<Category, Long> {
    @Query(value = "select c from Category c join fetch c.products", countQuery = "select count(c) from Category c")
    Page<Category> pageWithProducts(Pageable pageable);
}

@Component
class PagingDemo implements CommandLineRunner {
    private final CategoryRepository categories;

    PagingDemo(CategoryRepository categories) {
        this.categories = categories;
    }

    @Override
    @Transactional(readOnly = true)
    public void run(String... args) {
        Page<Category> page = categories.pageWithProducts(PageRequest.of(0, 2));
        for (Category c : page) {
            System.out.println(c.getName() + ": " + c.getProducts().size() + " products");
        }
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
Terminal
$ ./mvnw -q spring-boot:run
Hibernate: select c1_0.id,c1_0.name,p1_0.category_id,p1_0.id,p1_0.name from (select c1_0.id,c1_0.name from category c1_0 where exists(select 1 from product p1_0 where c1_0.id=p1_0.category_id) offset ? rows fetch first ? rows only) c1_0(id,name) join product p1_0 on c1_0.id=p1_0.category_id
Hibernate: select count(c1_0.id) from category c1_0
Keyboards: 2 products
Mice: 2 products
What’s happening
  1. pageWithProducts combines a collection fetch join with a Pageable asking for 2 categories. The countQuery is given separately, because counting a fetch join makes no sense.
  2. Hibernate 7.4 didn't page in memory. It moved the paging into a subquery over category alone (offset ? rows fetch first ? rows only), and joined the products to just those two categories. Two categories, each with both products, and no warning.
  3. The subquery also has where exists(select 1 from product …): it keeps the inner-join meaning of join fetch, so a category without products wouldn't count towards the page.
  4. In an interview, give both halves: the problem (paging over a collection join cuts join rows, and older Hibernate paged in memory) and the safe pattern that works on every version: page the parent ids in one query, then fetch those parents with their children in a second.
AdvancedThe other N+1: an eager @ManyToOne

Leaving @ManyToOne on its default, EAGER, causes the problem from the other side: listing products loads each product's category with a separate query, even if you never touch the category.

src/main/resources/schema.sql
create table category (id bigint primary key, name varchar(50) not null);
create table product (
    id bigint primary key,
    name varchar(100) not null,
    category_id bigint not null references category (id)
);
src/main/resources/data.sql
insert into category values (1, 'Keyboards'), (2, 'Mice'), (3, 'Monitors');
insert into product values
    (1, 'Mechanical keyboard', 1), (2, 'Compact keyboard', 1),
    (3, 'Wireless mouse', 2), (4, 'Trackball', 2),
    (5, '27-inch monitor', 3), (6, '32-inch monitor', 3);
src/main/java/com/example/shop/Catalog.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;

@Entity
class Category {
    @Id
    private Long id;
    private String name;
}

@Entity
class Product {
    @Id
    private Long id;
    private String name;

    @ManyToOne
    private Category category;

    String getName() {
        return name;
    }
}

interface ProductRepository extends JpaRepository<Product, Long> {
}

@Component
class ListNames implements CommandLineRunner {
    private final ProductRepository products;

    ListNames(ProductRepository products) {
        this.products = products;
    }

    @Override
    public void run(String... args) {
        System.out.println(products.findAll().stream().map(Product::getName).toList());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
Terminal
$ ./mvnw -q spring-boot:run
Hibernate: select p1_0.id,p1_0.category_id,p1_0.name from product p1_0
Hibernate: select c1_0.id,c1_0.name from category c1_0 where c1_0.id=?
Hibernate: select c1_0.id,c1_0.name from category c1_0 where c1_0.id=?
Hibernate: select c1_0.id,c1_0.name from category c1_0 where c1_0.id=?
[Mechanical keyboard, Compact keyboard, Wireless mouse, Trackball, 27-inch monitor, 32-inch monitor]
What’s happening
  1. @ManyToOne with no fetch attribute is EAGER. The runner only prints product names; it never looks at a category.
  2. findAll() runs one select on product. Then, because the category must be loaded eagerly and the JPQL query didn't join it, Hibernate runs select … from category … where c1_0.id=? once per distinct category: three extra queries before the list is even returned.
  3. Eager doesn't mean "joined"; it means "loaded no matter what", and for a query that's often one extra select per row. The common advice, and the one to give in an interview: make every @ManyToOne and @OneToOne LAZY, and fetch what each use case needs with a fetch join or entity graph.

#Lazy loading, LazyInitializationException and open-in-view

Added

A lazy association is a promise: "I'll run a query when you touch me". That promise can only be kept while the persistence context is open, which means inside the transaction that loaded the entity. Touch the collection after the transaction ended (the entity is detached) and Hibernate has no connection to run the query with. It throws LazyInitializationException.

It usually happens like this: a service method (or a repository call, which has its own short transaction) returns an entity, the transaction closes, and code further out (a controller, a JSON serialiser walking the object) touches a lazy field. In Node terms, it's like a database cursor you iterate after the connection was released.

src/main/resources/schema.sql
create table category (id bigint primary key, name varchar(50) not null);
create table product (
    id bigint primary key,
    name varchar(100) not null,
    category_id bigint not null references category (id)
);
src/main/resources/data.sql
insert into category values (1, 'Keyboards'), (2, 'Mice');
insert into product values (1, 'Mechanical keyboard', 1), (2, 'Compact keyboard', 1), (3, 'Wireless mouse', 2);
src/main/java/com/example/shop/Catalog.java
package com.example.shop;

import java.util.ArrayList;
import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import org.springframework.data.jpa.repository.JpaRepository;

@Entity
class Category {
    @Id
    private Long id;
    private String name;

    @OneToMany(mappedBy = "category")
    private List<Product> products = new ArrayList<>();

    String getName() {
        return name;
    }

    List<Product> getProducts() {
        return products;
    }
}

@Entity
class Product {
    @Id
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private Category category;

    String getName() {
        return name;
    }
}

interface CategoryRepository extends JpaRepository<Category, Long> {
}
src/main/java/com/example/shop/LazyDemo.java
package com.example.shop;

import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
class CatalogService {
    private final CategoryRepository categories;

    CatalogService(CategoryRepository categories) {
        this.categories = categories;
    }

    @Transactional(readOnly = true)
    public List<String> productNames(long categoryId) {
        Category category = categories.findById(categoryId).orElseThrow();
        return category.getProducts().stream().map(Product::getName).toList();
    }
}

@Component
class LazyDemo implements CommandLineRunner {
    private final CategoryRepository categories;
    private final CatalogService catalog;

    LazyDemo(CategoryRepository categories, CatalogService catalog) {
        this.categories = categories;
        this.catalog = catalog;
    }

    @Override
    public void run(String... args) {
        Category keyboards = categories.findById(1L).orElseThrow();
        System.out.println("loaded " + keyboards.getName());
        try {
            System.out.println(keyboards.getProducts().size());
        } catch (RuntimeException e) {
            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
        System.out.println("inside a transaction: " + catalog.productNames(1L));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=none
Terminal
$ ./mvnw -q spring-boot:run
loaded Keyboards
LazyInitializationException: Cannot lazily initialize collection of role 'com.example.shop.Category.products' with key '1' (no session)
inside a transaction: [Mechanical keyboard, Compact keyboard]
What’s happening
  1. categories.findById(1L) runs in the repository's own transaction. It loads the category row and leaves products as an uninitialised collection. The transaction ends as findById returns, so keyboards is detached. Reading its name works: loaded Keyboards, because name was loaded with the row.
  2. getProducts().size() needs the product rows. Hibernate checks for an open session to run the query with, finds none, and throws: LazyInitializationException: Cannot lazily initialize collection of role 'com.example.shop.Category.products' with key '1' (no session). The message names the exact association (Category.products) and row (key 1). (Older Hibernate versions word it as "failed to lazily initialize a collection of role … could not initialize proxy - no Session"; you'll see both in Stack Overflow answers.)
  3. CatalogService.productNames does the same work inside a @Transactional method: the session is open while the collection is touched, so Hibernate runs the product query and the method returns plain strings, [Mechanical keyboard, Compact keyboard].
  4. That's the general fix: do everything that needs the database inside the transaction and return data that doesn't need it (DTOs, records, strings). Fetch what you'll need with an entity graph or fetch join when you can, so it's one query rather than lazy loads.
AdvancedGotcha: EAGER and lazy_load_no_trans are wrong fixes
AdvancedOpen-in-view: why the exception "never happens" in web apps

In a Spring MVC app the same code often works, because Spring Boot turns on open-in-view (OSIV) by default for web applications: a web interceptor opens the persistence context when the request arrives and closes it after the response is written. Lazy loads in the controller, or during JSON serialisation, find the session open. Boot knows that's debatable, so it logs a warning at startup unless you set the property either way. The same controller, run twice:

src/main/resources/schema.sql
create table category (id bigint primary key, name varchar(50) not null);
create table product (
    id bigint primary key,
    name varchar(100) not null,
    category_id bigint not null references category (id)
);
src/main/resources/data.sql
insert into category values (1, 'Keyboards'), (2, 'Mice');
insert into product values (1, 'Mechanical keyboard', 1), (2, 'Compact keyboard', 1), (3, 'Wireless mouse', 2);
src/main/java/com/example/shop/Catalog.java
package com.example.shop;

import java.util.ArrayList;
import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import org.springframework.data.jpa.repository.JpaRepository;

@Entity
class Category {
    @Id
    private Long id;
    private String name;

    @OneToMany(mappedBy = "category")
    private List<Product> products = new ArrayList<>();

    List<Product> getProducts() {
        return products;
    }
}

@Entity
class Product {
    @Id
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private Category category;

    String getName() {
        return name;
    }
}

interface CategoryRepository extends JpaRepository<Category, Long> {
}
src/main/java/com/example/shop/CategoryController.java
package com.example.shop;

import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
class CategoryController {
    private final CategoryRepository categories;

    CategoryController(CategoryRepository categories) {
        this.categories = categories;
    }

    @GetMapping("/categories/{id}/products")
    List<String> productNames(@PathVariable long id) {
        Category category = categories.findById(id).orElseThrow();
        return category.getProducts().stream().map(Product::getName).toList();
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.banner-mode=off
logging.level.root=warn
logging.level.com.example.shop=info
spring.jpa.hibernate.ddl-auto=none
Terminal
$ ./mvnw -q -DskipTests package
$ java -jar target/shop-0.0.1-SNAPSHOT.jar &
2026-11-26T15:39:54.972Z  INFO 34457 --- [shop] [           main] com.example.shop.ShopApplication         : Starting ShopApplication v0.0.1-SNAPSHOT using Java 25.0.5.1 with PID 34457 (<project>/target/shop-0.0.1-SNAPSHOT.jar started by <user> in <project>)
2026-11-26T15:39:54.975Z  INFO 34457 --- [shop] [           main] com.example.shop.ShopApplication         : No active profile set, falling back to 1 default profile: "default"
2026-11-26T15:39:59.945Z  WARN 34457 --- [shop] [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2026-11-26T15:40:00.607Z  INFO 34457 --- [shop] [           main] com.example.shop.ShopApplication         : Started ShopApplication in 6.049 seconds (process running for 6.556)
$ curl -s localhost:8080/categories/1/products
["Mechanical keyboard","Compact keyboard"]
$ java -jar target/shop-0.0.1-SNAPSHOT.jar --spring.jpa.open-in-view=false &
2026-11-26T15:40:02.972Z  INFO 34747 --- [shop] [           main] com.example.shop.ShopApplication         : Starting ShopApplication v0.0.1-SNAPSHOT using Java 25.0.5.1 with PID 34747 (<project>/target/shop-0.0.1-SNAPSHOT.jar started by <user> in <project>)
2026-11-26T15:40:02.977Z  INFO 34747 --- [shop] [           main] com.example.shop.ShopApplication         : No active profile set, falling back to 1 default profile: "default"
2026-11-26T15:40:09.054Z  INFO 34747 --- [shop] [           main] com.example.shop.ShopApplication         : Started ShopApplication in 6.906 seconds (process running for 7.542)
$ curl -s localhost:8080/categories/1/products
{"timestamp":"2026-11-26T15:40:09.765Z","status":500,"error":"Internal Server Error","path":"/categories/1/products"}
What’s happening
  1. This is a web app (no web-application-type=none), with the log at warn except for the app's own package at info, so the startup shows the app's own lines plus any warnings. The controller does what the runner above did: findById, then touch the lazy products collection outside any @Transactional. (Chapter 13 covers controllers.)
  2. The first start prints Boot's warning: spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning.
  3. The request works: ["Mechanical keyboard","Compact keyboard"]. The repository's transaction ended inside findById, but OSIV kept the persistence context open for the whole request, so the lazy load ran a query from the controller, outside any transaction.
  4. Then the app is started again with --spring.jpa.open-in-view=false (the checker stops the first app first; by hand you'd stop it with kill %1). No warning this time, because the property is set explicitly.
  5. The same request now fails with a 500: Boot's default error body, "status":500,"error":"Internal Server Error". The server log (not shown, it's printed after startup) has the reason: LazyInitializationException: Cannot lazily initialize collection of role 'com.example.shop.Category.products' with key '1' (no session), exactly as in the runner.
  6. So OSIV doesn't fix lazy loading; it hides it. With it on, queries run from controllers and serialisers, each lazy load is a query nobody planned, and the database connection is held for the whole request, including the time spent writing the response.

#@Transactional

Added

A transaction groups statements so they all succeed or all disappear. In Spring you rarely write begin and commit; you put @Transactional on a service method, and the bean's proxy (chapter 12) starts a transaction before the method and ends it after. The mental model: the method boundary is the transaction boundary. Return normally and it commits; throw, and it may roll back. In Node, the closest thing is Prisma's prisma.$transaction(async (tx) => { … }), except that Spring's version is declarative and the transaction follows the thread into every repository call, without passing a tx around.

"May" is the part interviewers probe. By default Spring rolls back on unchecked exceptions (RuntimeException and its subclasses) and on Error, but not on checked exceptions. The reasoning goes back to EJB: a checked exception was meant as a business outcome the caller handles, not a failure. Most people expect the opposite, and it's a real source of half-saved data.

The defaults, from the Spring Framework docs:

AttributeDefaultNotes
propagationREQUIREDjoin the caller's transaction, or start one
isolationDEFAULTthe database's own default (READ COMMITTED on PostgreSQL)
readOnlyfalsetrue lets Hibernate skip dirty checking and flushing
rollbackRuntimeException and Errorchange with rollbackFor / noRollbackFor
src/main/java/com/example/shop/Orders.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Entity
@Table(name = "orders")
class Order {
    @Id
    @GeneratedValue
    private Long id;
    private String item;

    protected Order() {
    }

    Order(String item) {
        this.item = item;
    }

    String getItem() {
        return item;
    }
}

interface OrderRepository extends JpaRepository<Order, Long> {
}

class PaymentDeclinedException extends Exception {
    PaymentDeclinedException(String message) {
        super(message);
    }
}

@Service
class OrderService {
    private final OrderRepository orders;

    OrderService(OrderRepository orders) {
        this.orders = orders;
    }

    @Transactional
    public void placeThenFailUnchecked(String item) {
        orders.save(new Order(item));
        throw new IllegalStateException("out of stock");
    }

    @Transactional
    public void placeThenFailChecked(String item) throws PaymentDeclinedException {
        orders.save(new Order(item));
        throw new PaymentDeclinedException("card declined");
    }

    @Transactional(rollbackFor = PaymentDeclinedException.class)
    public void placeThenFailCheckedWithRollbackFor(String item) throws PaymentDeclinedException {
        orders.save(new Order(item));
        throw new PaymentDeclinedException("card declined");
    }
}

@Component
class RollbackDemo implements CommandLineRunner {
    private final OrderService service;
    private final OrderRepository orders;

    RollbackDemo(OrderService service, OrderRepository orders) {
        this.service = service;
        this.orders = orders;
    }

    @Override
    public void run(String... args) {
        try {
            service.placeThenFailUnchecked("Keyboard");
        } catch (IllegalStateException e) {
            System.out.println("unchecked, " + e.getMessage() + " -> orders in table: " + orders.count());
        }
        try {
            service.placeThenFailChecked("Mouse");
        } catch (PaymentDeclinedException e) {
            System.out.println("checked, " + e.getMessage() + " -> orders in table: " + orders.count());
        }
        try {
            service.placeThenFailCheckedWithRollbackFor("Monitor");
        } catch (PaymentDeclinedException e) {
            System.out.println("rollbackFor, " + e.getMessage() + " -> orders in table: " + orders.count());
        }
        orders.findAll().forEach(o -> System.out.println("saved: " + o.getItem()));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
unchecked, out of stock -> orders in table: 0
checked, card declined -> orders in table: 1
rollbackFor, card declined -> orders in table: 1
saved: Mouse
What’s happening
  1. The table is called orders because order is a reserved word in SQL (@Table sets the name). Each service method saves an order and then throws, in its own transaction; the runner counts the rows after each call.
  2. placeThenFailUnchecked throws IllegalStateException, a RuntimeException. The proxy sees it leave the method and rolls back: the insert is undone, orders in table: 0.
  3. placeThenFailChecked throws PaymentDeclinedException, which extends Exception, so it's checked. The proxy rethrows it to the caller but commits first: orders in table: 1. The caller got an exception and the order was saved anyway, which is rarely what anyone wanted.
  4. placeThenFailCheckedWithRollbackFor is the same method with rollbackFor = PaymentDeclinedException.class. Now that exception rolls back too, and the count stays at 1.
  5. Only the mouse order survived (saved: Mouse). Rule of thumb: make domain exceptions extend RuntimeException (most modern Java and Spring code does, as chapter 06 says), or list checked ones in rollbackFor. The Spring docs now also offer a global switch: @EnableTransactionManagement(rollbackOn = RollbackOn.ALL_EXCEPTIONS) (Spring 6.2+).
AdvancedGotcha: calls that skip the transaction proxy
AdvancedTip: where to put @Transactional
AdvancedPropagation: REQUIRED, REQUIRES_NEW and the rollback-only trap

Propagation decides what happens when a transactional method calls another one. With the default, REQUIRED, the inner method joins the outer transaction: one physical transaction, so one failure anywhere rolls back everything. REQUIRES_NEW suspends the outer transaction and runs the inner method in its own, committed or rolled back independently: right for an audit log that must survive a failed business operation. The trap is the combination of REQUIRED and catching: if an inner @Transactional method throws, it marks the shared transaction rollback-only, even if the outer method catches the exception and carries on.

src/main/java/com/example/shop/Propagation.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Entity
@Table(name = "orders")
class Order {
    @Id
    @GeneratedValue
    private Long id;
    private String item;

    protected Order() {
    }

    Order(String item) {
        this.item = item;
    }
}

@Entity
class AuditEntry {
    @Id
    @GeneratedValue
    private Long id;
    private String message;

    protected AuditEntry() {
    }

    AuditEntry(String message) {
        this.message = message;
    }
}

interface OrderRepository extends JpaRepository<Order, Long> {
}

interface AuditRepository extends JpaRepository<AuditEntry, Long> {
}

@Service
class AuditService {
    private final AuditRepository audit;

    AuditService(AuditRepository audit) {
        this.audit = audit;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void record(String message) {
        audit.save(new AuditEntry(message));
    }
}

@Service
class StockService {
    @Transactional
    public void reserve(String item) {
        throw new IllegalStateException(item + " is out of stock");
    }
}

@Service
class OrderService {
    private final OrderRepository orders;
    private final AuditService audit;
    private final StockService stock;

    OrderService(OrderRepository orders, AuditService audit, StockService stock) {
        this.orders = orders;
        this.audit = audit;
        this.stock = stock;
    }

    @Transactional
    public void placeAndFail(String item) {
        orders.save(new Order(item));
        audit.record("tried to order " + item);
        throw new IllegalStateException("payment failed");
    }

    @Transactional
    public void placeIgnoringStock(String item) {
        orders.save(new Order(item));
        try {
            stock.reserve(item);
        } catch (IllegalStateException e) {
            System.out.println("caught: " + e.getMessage());
        }
    }
}

@Component
class PropagationDemo implements CommandLineRunner {
    private final OrderService service;
    private final OrderRepository orders;
    private final AuditRepository audit;

    PropagationDemo(OrderService service, OrderRepository orders, AuditRepository audit) {
        this.service = service;
        this.orders = orders;
        this.audit = audit;
    }

    @Override
    public void run(String... args) {
        try {
            service.placeAndFail("Keyboard");
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage() + " -> orders: " + orders.count() + ", audit entries: " + audit.count());
        }
        try {
            service.placeIgnoringStock("Mouse");
        } catch (UnexpectedRollbackException e) {
            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
            System.out.println("orders: " + orders.count());
        }
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
payment failed -> orders: 0, audit entries: 1
caught: Mouse is out of stock
UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
orders: 0
What’s happening
  1. placeAndFail starts transaction A, saves an order in it, then calls audit.record. That method is REQUIRES_NEW, so Spring suspends A, starts transaction B, saves the audit entry and commits B before returning.
  2. Back in A, the method throws a RuntimeException, so A rolls back. Result: orders: 0, audit entries: 1. The audit entry survived the failure, which is the point of REQUIRES_NEW. (It needs a second database connection while A is suspended, so the pool must allow it.)
  3. placeIgnoringStock starts transaction C and saves an order. stock.reserve is @Transactional with the default REQUIRED, so it joins C. It throws; as the exception passes through reserve's proxy, Spring marks C rollback-only.
  4. The outer method catches the exception (caught: Mouse is out of stock) and returns normally, expecting a commit. But C is marked rollback-only, so Spring rolls back and throws UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only. The order is gone: orders: 0.
  5. Fixes: don't make reserve transactional if it only validates, let the exception propagate, or give the inner work its own transaction (REQUIRES_NEW) if it may fail independently. NESTED is a third option: it uses a JDBC savepoint inside the outer transaction, and the Spring docs say it works only with JDBC resources, so don't rely on it for work done through JPA.

#Schema migrations with Flyway

Added

So far Hibernate created the tables (ddl-auto, the default for embedded databases) or schema.sql did. Neither works for a production database that already holds data. You need migrations: numbered SQL scripts that move the schema from one version to the next, applied once each, in order, and recorded in a table. In Node that's Prisma Migrate, Knex or TypeORM migrations; in Spring Boot it's Flyway (or Liquibase).

Flyway's model is a ledger. Files live in src/main/resources/db/migration and are named V<version>__<description>.sql (two underscores): V1__create_product.sql, V2__add_stock.sql. At startup Flyway compares the files with its history table, flyway_schema_history, runs the ones not yet applied, and records each with a checksum. Editing an applied file changes its checksum, and Flyway refuses to start: migrations are append-only.

In Boot 4 Flyway needs its own starter (Boot 3 only needed flyway-core on the classpath). Add this to pom.xml:

pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-flyway</artifactId>
		</dependency>
src/main/resources/db/migration/V1__create_product.sql
create table product (
    id bigint generated by default as identity primary key,
    name varchar(100) not null,
    price_cents bigint not null
);
insert into product (name, price_cents) values ('Mechanical keyboard', 8999), ('Wireless mouse', 2999);
src/main/resources/db/migration/V2__add_stock.sql
alter table product add column stock int not null default 0;
update product set stock = 12 where name = 'Wireless mouse';
src/main/java/com/example/shop/Products.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;

@Entity
class Product {
    @Id
    private Long id;
    private String name;
    private long priceCents;
    private int stock;

    @Override
    public String toString() {
        return name + ": stock " + stock;
    }
}

interface ProductRepository extends JpaRepository<Product, Long> {
}

@Component
class ShowProducts implements CommandLineRunner {
    private final ProductRepository products;
    private final Flyway flyway;

    ShowProducts(ProductRepository products, Flyway flyway) {
        this.products = products;
        this.flyway = flyway;
    }

    @Override
    public void run(String... args) {
        for (MigrationInfo m : flyway.info().applied()) {
            System.out.println("V" + m.getVersion() + " " + m.getDescription() + ": " + m.getState());
        }
        products.findAll().forEach(System.out::println);
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=validate
Terminal
$ ./mvnw -q spring-boot:run
2026-11-26T15:40:17.457Z  WARN 35413 --- [shop] [           main] o.f.c.internal.database.base.Database    : Using H2 2.5.252 which is newer than the version Flyway has been verified with. The latest verified version of H2 is 2.3.232.
2026-11-26T15:40:20.001Z  WARN 35413 --- [shop] [           main] o.f.c.internal.database.base.Database    : Using H2 2.5.252 which is newer than the version Flyway has been verified with. The latest verified version of H2 is 2.3.232.
V1 create product: SUCCESS
V2 add stock: SUCCESS
Mechanical keyboard: stock 0
Wireless mouse: stock 12
What’s happening
  1. With spring-boot-starter-flyway on the classpath, Boot runs Flyway before JPA starts: it finds the two files under db/migration, creates flyway_schema_history, and applies V1 then V2. H2 support is built into Flyway's core; for PostgreSQL you'd also add org.flywaydb:flyway-database-postgresql (start.spring.io adds it when you pick both, along with a spring-boot-starter-flyway-test test starter).
  2. The two WARN lines are real: Boot 4.2 ships H2 2.5.252, and Flyway says it has only been verified with H2 up to 2.3.232. It's printed each time Flyway connects: once for the migration at startup, once for the runner's info() call. Harmless here, and a reminder that H2 isn't your production database.
  3. spring.jpa.hibernate.ddl-auto=validate changes Hibernate's role: instead of creating tables, it checks that every entity field has a matching column and fails startup if not. Flyway owns the schema; Hibernate only verifies it.
  4. The runner asks the Flyway bean what it applied: V1 create product: SUCCESS and V2 add stock: SUCCESS (the description comes from the file name, underscores turned into spaces).
  5. The products show V2's work: the new stock column defaulted to 0 for the keyboard, and the update set the mouse to 12. Start the app again against a persistent database and Flyway would apply nothing, because both versions are already in the history table.
AdvancedWhat validate catches

Add a field to the entity without writing a migration for it, and validate stops the app before it can fail at the first query. Here the entity gained a colour field that no migration created:

pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-flyway</artifactId>
		</dependency>
src/main/resources/db/migration/V1__create_product.sql
create table product (
    id bigint generated by default as identity primary key,
    name varchar(100) not null,
    price_cents bigint not null
);
src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
class Product {
    @Id
    private Long id;
    private String name;
    private long priceCents;
    private String colour;
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=validate
Terminal
$ ./mvnw -q spring-boot:run 2>&1 | grep -o "Schema validation: .*" | head -1
Schema validation: missing column [colour] in table [product]
What’s happening
  1. Flyway runs V1, which creates product with three columns. Then Hibernate starts with ddl-auto=validate and compares each entity with the real tables.
  2. colour maps to a colour column that doesn't exist, so building the EntityManagerFactory fails and the app doesn't start. The grep keeps the line that matters from the long stack trace: Schema validation: missing column [colour] in table [product].
  3. The fix is a V2__add_colour.sql, not editing V1 (already applied on other environments, and Flyway would reject the changed checksum). This check in CI is cheap insurance against an entity and the schema drifting apart.

#JdbcClient when JPA is too much

Added

JPA earns its keep when you load entities, change them and let Hibernate write the changes. For reports, bulk updates, or queries that are naturally SQL, it's overhead: entities, a persistence context and generated SQL you then have to inspect. Spring's answer is JdbcClient (Spring 6.1+): a fluent API over plain JDBC. You write the SQL, bind parameters by name or position, and map rows to records. It's the Java version of using pg or postgres.js directly instead of an ORM, and Boot auto-configures one for the same DataSource JPA uses.

src/main/resources/schema.sql
create table product (
    id bigint generated by default as identity primary key,
    name varchar(100) not null,
    price_cents bigint not null
);
src/main/resources/data.sql
insert into product (name, price_cents) values
    ('Mechanical keyboard', 8999), ('Wireless mouse', 2999), ('27-inch monitor', 29999);
src/main/java/com/example/shop/ProductDao.java
package com.example.shop;

import java.util.List;
import java.util.Optional;

import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

record ProductRow(long id, String name, long priceCents) {
}

@Repository
class ProductDao {
    private final JdbcClient jdbc;

    ProductDao(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    List<ProductRow> cheaperThan(long cents) {
        return jdbc.sql("select id, name, price_cents from product where price_cents < :max order by price_cents")
                .param("max", cents)
                .query(ProductRow.class)
                .list();
    }

    Optional<ProductRow> findById(long id) {
        return jdbc.sql("select id, name, price_cents from product where id = ?")
                .param(id)
                .query(ProductRow.class)
                .optional();
    }

    long insert(String name, long cents) {
        KeyHolder keys = new GeneratedKeyHolder();
        jdbc.sql("insert into product (name, price_cents) values (:name, :cents)")
                .param("name", name)
                .param("cents", cents)
                .update(keys);
        return keys.getKey().longValue();
    }

    int raiseAllBy(int percent) {
        return jdbc.sql("update product set price_cents = price_cents * (100 + :p) / 100")
                .param("p", percent)
                .update();
    }

    long total() {
        return jdbc.sql("select sum(price_cents) from product").query(Long.class).single();
    }
}

@Component
class JdbcDemo implements CommandLineRunner {
    private final ProductDao dao;

    JdbcDemo(ProductDao dao) {
        this.dao = dao;
    }

    @Override
    public void run(String... args) {
        System.out.println(dao.cheaperThan(10000));
        System.out.println(dao.findById(3));
        System.out.println(dao.findById(99));
        System.out.println("new id: " + dao.insert("Trackball", 5999));
        System.out.println("rows updated: " + dao.raiseAllBy(10));
        System.out.println("total: " + dao.total());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=none
Terminal
$ ./mvnw -q spring-boot:run
[ProductRow[id=2, name=Wireless mouse, priceCents=2999], ProductRow[id=1, name=Mechanical keyboard, priceCents=8999]]
Optional[ProductRow[id=3, name=27-inch monitor, priceCents=29999]]
Optional.empty
new id: 4
rows updated: 4
total: 52792
What’s happening
  1. JdbcClient is injected like any bean; Boot built it from the same connection pool JPA uses (the starter's data-jpa pulls in JDBC). @Repository adds Spring's translation of SQL exceptions into DataAccessException.
  2. cheaperThan binds :max by name and maps each row with query(ProductRow.class): Spring matches columns to the record's components, turning price_cents into priceCents by itself. Two rows under 10000 cents, cheapest first.
  3. findById uses a positional ? instead. .optional() returns Optional[ProductRow[...]] for id 3 and Optional.empty for 99; .single() would throw when there's no row, .list() returns all rows.
  4. insert passes a KeyHolder to update to get the generated id back: new id: 4. raiseAllBy(10) is one UPDATE for all rows, and update() returns how many it changed: rows updated: 4. Loading four entities and changing each would have cost a select and four updates.
  5. total() maps a single column to Long. The integer arithmetic in the update truncates (8999 × 110 / 100 = 9898.9 becomes 9898), so the four prices sum to total: 52792. Plain SQL, plain results, and nothing happens that you didn't write.
AdvancedTip: mixing JPA and JdbcClient

#Your turn: data access

Added
Your turn: the two most expensive in a category

Using the product table from the queries example, add a derived query (no @Query) that returns the two most expensive products in a category, and print it for "mice".

Show answer
src/main/resources/schema.sql
create table product (
    id bigint primary key,
    name varchar(100) not null,
    category varchar(50) not null,
    price_cents bigint not null
);
src/main/resources/data.sql
insert into product values
    (1, 'Mechanical keyboard', 'keyboards', 8999),
    (2, 'Compact keyboard', 'keyboards', 4999),
    (3, 'Wireless mouse', 'mice', 2999),
    (4, 'Trackball', 'mice', 5999),
    (5, 'Gaming mouse', 'mice', 6999),
    (6, '27-inch monitor', 'monitors', 29999);
src/main/java/com/example/shop/Products.java
package com.example.shop;

import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;

@Entity
class Product {
    @Id
    private Long id;
    private String name;
    private String category;
    private long priceCents;

    @Override
    public String toString() {
        return name + " (" + priceCents + ")";
    }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findTop2ByCategoryOrderByPriceCentsDesc(String category);
}

@Component
class TopTwo implements CommandLineRunner {
    private final ProductRepository products;

    TopTwo(ProductRepository products) {
        this.products = products;
    }

    @Override
    public void run(String... args) {
        System.out.println(products.findTop2ByCategoryOrderByPriceCentsDesc("mice"));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
Terminal
$ ./mvnw -q spring-boot:run
Hibernate: select p1_0.id,p1_0.category,p1_0.name,p1_0.price_cents from product p1_0 where p1_0.category=? order by p1_0.price_cents desc fetch first ? rows only
[Gaming mouse (6999), Trackball (5999)]
What’s happening
  1. findTop2By… limits the result to two rows; Category adds the where, and OrderByPriceCentsDesc sorts most expensive first.
  2. The SQL log shows Spring Data turned Top2 into fetch first ? rows only, so the database does the limiting; only two rows travel over the wire.
  3. It prints [Gaming mouse (6999), Trackball (5999)]. First2 means the same as Top2.
Your turn: products with their category in one query

Products point at their category with a lazy @ManyToOne. Printing every product with its category name currently takes 1 + 3 queries. Add a repository method that loads them in one query, and print the statement count to prove it.

Show answer
src/main/resources/schema.sql
create table category (id bigint primary key, name varchar(50) not null);
create table product (
    id bigint primary key,
    name varchar(100) not null,
    category_id bigint not null references category (id)
);
src/main/resources/data.sql
insert into category values (1, 'Keyboards'), (2, 'Mice'), (3, 'Monitors');
insert into product values
    (1, 'Mechanical keyboard', 1), (2, 'Wireless mouse', 2), (3, '27-inch monitor', 3);
src/main/java/com/example/shop/Catalog.java
package com.example.shop;

import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Entity
class Category {
    @Id
    private Long id;
    private String name;

    String getName() {
        return name;
    }
}

@Entity
class Product {
    @Id
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private Category category;

    String getName() {
        return name;
    }

    Category getCategory() {
        return category;
    }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    @EntityGraph(attributePaths = "category")
    @Query("select p from Product p order by p.id")
    List<Product> findAllWithCategory();
}

@Service
class Listing {
    private final ProductRepository products;

    Listing(ProductRepository products) {
        this.products = products;
    }

    @Transactional(readOnly = true)
    public void print() {
        for (Product p : products.findAllWithCategory()) {
            System.out.println(p.getName() + " in " + p.getCategory().getName());
        }
    }
}

@Component
class ListingDemo implements CommandLineRunner {
    private final Listing listing;
    private final Statistics stats;

    ListingDemo(Listing listing, EntityManagerFactory emf) {
        this.listing = listing;
        this.stats = emf.unwrap(SessionFactory.class).getStatistics();
    }

    @Override
    public void run(String... args) {
        stats.clear();
        listing.print();
        System.out.println("queries: " + stats.getPrepareStatementCount());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.generate_statistics=true
Terminal
$ ./mvnw -q spring-boot:run
Mechanical keyboard in Keyboards
Wireless mouse in Mice
27-inch monitor in Monitors
queries: 1
What’s happening
  1. @EntityGraph(attributePaths = "category") on the @Query method tells Hibernate to load each product's category in the same query, with a join, instead of leaving a lazy proxy.
  2. The loop calls p.getCategory().getName(). The category objects are already loaded, so no extra query runs; with plain findAll() each distinct category would have cost one more select.
  3. It prints the three products with their categories and queries: 1. A JPQL join fetch p.category would also give one query.
Your turn: roll back on a checked exception

placeOrder saves an order and then throws the checked PaymentDeclinedException, and the order stays in the table. Change only the annotation so the order is rolled back, and print the row count to prove it.

Show answer
src/main/java/com/example/shop/Orders.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Entity
@Table(name = "orders")
class Order {
    @Id
    @GeneratedValue
    private Long id;
    private String item;

    protected Order() {
    }

    Order(String item) {
        this.item = item;
    }
}

interface OrderRepository extends JpaRepository<Order, Long> {
}

class PaymentDeclinedException extends Exception {
    PaymentDeclinedException(String message) {
        super(message);
    }
}

@Service
class OrderService {
    private final OrderRepository orders;

    OrderService(OrderRepository orders) {
        this.orders = orders;
    }

    @Transactional(rollbackFor = PaymentDeclinedException.class)
    public void placeOrder(String item) throws PaymentDeclinedException {
        orders.save(new Order(item));
        throw new PaymentDeclinedException("card declined");
    }
}

@Component
class Checkout implements CommandLineRunner {
    private final OrderService service;
    private final OrderRepository orders;

    Checkout(OrderService service, OrderRepository orders) {
        this.service = service;
        this.orders = orders;
    }

    @Override
    public void run(String... args) {
        try {
            service.placeOrder("Keyboard");
        } catch (PaymentDeclinedException e) {
            System.out.println(e.getMessage() + " -> orders in table: " + orders.count());
        }
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
card declined -> orders in table: 0
What’s happening
  1. Without rollbackFor, the proxy commits when a checked exception leaves the method, so the count would be 1.
  2. rollbackFor = PaymentDeclinedException.class adds that exception (and its subclasses) to the rollback rules. The insert is undone before the exception reaches the caller.
  3. It prints card declined -> orders in table: 0. The other fix is to make PaymentDeclinedException extend RuntimeException, which rolls back by default.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.