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.
repositories on top: you declare an interface, Spring generates the implementation
a 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.
$ ./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
@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).
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.
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.
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.
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.
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.
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:
Method
What 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.
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.
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.
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.
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.
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
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
createtable product (
id bigintprimarykey,
name varchar(100)notnull,
category varchar(50)notnull,
price_cents bigintnotnull);
packagecom.example.shop;importjava.util.List;importjakarta.persistence.Entity;importjakarta.persistence.Id;importorg.springframework.data.domain.Page;importorg.springframework.data.domain.Pageable;importorg.springframework.data.jpa.repository.JpaRepository;importorg.springframework.data.jpa.repository.Query;importorg.springframework.data.repository.query.Param;@EntityclassProduct{@IdprivateLong id;privateString name;privateString category;privatelong priceCents;@OverridepublicStringtoString(){return name +" ("+ priceCents +")";}}interfaceProductRepositoryextendsJpaRepository<Product,Long>{List<Product>findByCategoryOrderByPriceCentsDesc(String category);List<Product>findByNameContainingIgnoreCase(String text);longcountByPriceCentsLessThan(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)ProductmostExpensive();Page<Product>findByCategory(String category,Pageable pageable);}
src/main/java/com/example/shop/QueryDemo.java
packagecom.example.shop;importorg.springframework.boot.CommandLineRunner;importorg.springframework.data.domain.Page;importorg.springframework.data.domain.PageRequest;importorg.springframework.data.domain.Sort;importorg.springframework.stereotype.Component;@ComponentclassQueryDemoimplementsCommandLineRunner{privatefinalProductRepository products;QueryDemo(ProductRepository products){this.products = products;}@Overridepublicvoidrun(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");}}
$ ./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
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.
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.
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).
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.
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:
$ ./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
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.
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'.
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.
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
createtable category (id bigintprimarykey, name varchar(50)notnull);createtable product (
id bigintprimarykey,
name varchar(100)notnull,
price_cents bigintnotnull,
category_id bigintnotnullreferences category (id));
packagecom.example.shop;importjava.util.ArrayList;importjava.util.List;importjakarta.persistence.Entity;importjakarta.persistence.FetchType;importjakarta.persistence.Id;importjakarta.persistence.ManyToOne;importjakarta.persistence.OneToMany;importorg.springframework.data.jpa.repository.EntityGraph;importorg.springframework.data.jpa.repository.JpaRepository;importorg.springframework.data.jpa.repository.Query;@EntityclassCategory{@IdprivateLong id;privateString name;@OneToMany(mappedBy ="category")privateList<Product> products =newArrayList<>();StringgetName(){return name;}List<Product>getProducts(){return products;}}@EntityclassProduct{@IdprivateLong id;privateString name;privatelong priceCents;@ManyToOne(fetch =FetchType.LAZY)privateCategory category;}interfaceCategoryRepositoryextendsJpaRepository<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();}
$ ./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
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.
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.
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.
@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.
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.
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
createtable category (id bigintprimarykey, name varchar(50)notnull);createtable product (
id bigintprimarykey,
name varchar(100)notnull,
category_id bigintnotnullreferences category (id));
$ ./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
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.
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.
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.
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
createtable category (id bigintprimarykey, name varchar(50)notnull);createtable product (
id bigintprimarykey,
name varchar(100)notnull,
category_id bigintnotnullreferences category (id));
$ ./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
@ManyToOne with no fetch attribute is EAGER. The runner only prints product names; it never looks at a category.
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.
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 @OneToOneLAZY, 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
createtable category (id bigintprimarykey, name varchar(50)notnull);createtable product (
id bigintprimarykey,
name varchar(100)notnull,
category_id bigintnotnullreferences category (id));
$ ./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
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.
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.)
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].
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
createtable category (id bigintprimarykey, name varchar(50)notnull);createtable product (
id bigintprimarykey,
name varchar(100)notnull,
category_id bigintnotnullreferences category (id));
$ ./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
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.)
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.
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.
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.
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.
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.
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:
Attribute
Default
Notes
propagation
REQUIRED
join the caller's transaction, or start one
isolation
DEFAULT
the database's own default (READ COMMITTED on PostgreSQL)
readOnly
false
true lets Hibernate skip dirty checking and flushing
$ ./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
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.
placeThenFailUnchecked throws IllegalStateException, a RuntimeException. The proxy sees it leave the method and rolls back: the insert is undone, orders in table: 0.
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.
placeThenFailCheckedWithRollbackFor is the same method with rollbackFor = PaymentDeclinedException.class. Now that exception rolls back too, and the count stays at 1.
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.
$ ./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
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.
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.)
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.
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.
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.
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:
$ ./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
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).
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.
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.
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).
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:
Flyway runs V1, which creates product with three columns. Then Hibernate starts with ddl-auto=validate and compares each entity with the real tables.
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].
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.
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
createtable product (
id bigint generated bydefaultasidentityprimarykey,
name varchar(100)notnull,
price_cents bigintnotnull);
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.
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.
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.
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.
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.
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
createtable product (
id bigintprimarykey,
name varchar(100)notnull,
category varchar(50)notnull,
price_cents bigintnotnull);
$ ./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
findTop2By… limits the result to two rows; Category adds the where, and OrderByPriceCentsDesc sorts most expensive first.
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.
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
createtable category (id bigintprimarykey, name varchar(50)notnull);createtable product (
id bigintprimarykey,
name varchar(100)notnull,
category_id bigintnotnullreferences category (id));
$ ./mvnw -q spring-boot:run
Mechanical keyboard in Keyboards
Wireless mouse in Mice
27-inch monitor in Monitors
queries: 1
What’s happening
@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.
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.
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.
Without rollbackFor, the proxy commits when a checked exception leaves the method, so the count would be 1.
rollbackFor = PaymentDeclinedException.class adds that exception (and its subclasses) to the rollback rules. The insert is undone before the exception reaches the caller.
It prints card declined -> orders in table: 0. The other fix is to make PaymentDeclinedException extend RuntimeException, which rolls back by default.