dsl.fetch("select isbnn from book"). It compiles. The tests that do not touch that line pass. It ships. The first request that reaches it throws a BadSqlGrammarException in production. That is the cost of SQL as a string: the compiler cannot see inside it, so every typo, every renamed column and every wrong type waits for a runtime to be found.
jOOQ attacks exactly that. It reads your database schema and generates Java classes that mirror it (one constant per table, one typed field per column), then lets you build SQL by calling methods on those classes. A column that does not exist is a missing Java symbol, and a condition that compares a number with a string is a type error, both reported by javac before anything runs. It is not an ORM: you still think in SQL, joins and all, but the SQL is checked.
This post takes a first-time reader from an empty project to a working Spring Boot 4.2 application: Flyway migrations as the single source of truth, code generation from a real PostgreSQL, typed queries (including a nested-collection query, a CTE with a window function and an upsert), records instead of entities, Spring transactions, and tests against a real PostgreSQL 17 started by Testcontainers. Every SQL statement, error message and number below was printed by a real run of the companion module, and each block links to the file it came from. The deeper material lives in the collapsible sections, so you can read straight through or open only what you need.
Versions, all verified against Maven Central metadata and a real run. Spring Boot 4.2.0 (GA on 19 November 2026), jOOQ 3.21.9 (the version the Boot 4.2.0 BOM manages;3.21.10is already on Maven Central, so a project that overridesjooq.versioncan be a patch ahead), Flyway 12.11.0 (managed), PostgreSQL 17.12 (postgres:17-alpine) through Testcontainers 2.0.5, JDK Temurin 25.0.5.1, Maven 3.9.11, Docker 29.9.3. The captured startup lines are in 13-startup-log-lines.txt.
Why a SQL string is a bug waiting for a runtime
Start with the problem on its own, because it is the reason the rest exists. The test below sends a query with a misspelt column through jOOQ’s plain-SQL escape hatch. Nothing about it is wrong from Java’s point of view, so the compiler is silent and PostgreSQL is the first to notice. From QueryTests.java, the result is in 07-runtime-failure-of-plain-sql.txt:dsl.fetch("select isbnn from book") compiles fine and fails at runtime:
exception type: org.springframework.jdbc.BadSqlGrammarException
root cause: ERROR: column "isbnn" does not exist
Two details are worth noticing. The exception is Spring’s org.springframework.jdbc.BadSqlGrammarException, not a jOOQ type, because Spring Boot installs an exception translator on the DSLContext (more on what Boot wires up later). And the useful part, column "isbnn" does not exist, is the root cause at the bottom of the exception chain.
Going deeper
- The companion test that produced the output: QueryTests.java
- Related on this blog: JdbcClient in Spring Framework 7, the string-SQL option jOOQ is the typed alternative to, and MyBatis with Spring Boot 4, where statements are also checked only at runtime
The whole idea in one picture: the schema writes your Java
A relational schema already says what columns exist and what types they have. jOOQ’s code generator connects to a database, reads that schema, and writes Java source for it. Three kinds of class come out: a table class with one typed field per column (BOOK.TITLE is a TableField<BookRecord, String>), a record class that holds one row, and, if you ask for them, POJOs. You then build SQL by calling methods on those fields, and jOOQ renders the SQL text for your database dialect.
Intermediate: jOOQ is not an ORM, and what that means in practice
An ORM such as Hibernate keeps a persistence context: it remembers the entities it loaded, notices when you change one (dirty checking), loads related objects lazily, and writes the SQL for you. jOOQ has none of that. A select returns rows or records, an update is an UPDATE statement you wrote, and nothing is tracked between calls. You gain SQL you can read, predict and tune. You give up change tracking, lazy loading and cascades, so the relationships and the write order are yours to manage.
That is also why the two are not exclusive. Many Spring projects use JPA for plain create/read/update/delete and jOOQ for reports and hard queries, on the same DataSource. The transactions section shows both sharing one Spring transaction manager.
Going deeper
- jOOQ manual, the reference, and its code generation chapter
- This blog: Jakarta Data with Hibernate compares compile-time versus start-up errors on the JPA side
- This blog: Catch N+1 Queries Automatically in Hibernate 7, a problem jOOQ’s explicit joins do not have in the first place
Set it up: two starters, one easily missed Flyway module, two migrations
The application needs the jOOQ starter and the Flyway starter, and, for PostgreSQL, one extra artifact. The block below is from pom.xml; the versions come from the Spring Boot BOM, so none is written here.<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jooq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-flyway</artifactId>
</dependency>
<!-- Flyway 10+ ships database support as separate modules; without this: "Unsupported Database: PostgreSQL 17.12" -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Since Flyway 10, each database lives in its own module, and the Flyway starter does not bring the PostgreSQL one. Leave flyway-database-postgresql out and the application refuses to start. This is the real error from a copy of the module with that one dependency removed, written by missing-flyway-module.sh:
flyway-database-postgresql removed from the application dependencies
Caused by: org.flywaydb.core.api.FlywayException: Unsupported Database: PostgreSQL 17.12
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 9.266 s <<< FAILURE! -- in com.ankurm.jooq.JooqSliceTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
Now the schema. Flyway runs every V<n>__name.sql file in order and records what it ran. The first migration creates an enum type and three tables (from V1__bookshop.sql):
CREATE TYPE genre AS ENUM ('FICTION', 'SCIENCE', 'HISTORY', 'TECH');
CREATE TABLE author (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name TEXT NOT NULL,
country CHAR(2) NOT NULL
);
CREATE TABLE book (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
author_id BIGINT NOT NULL REFERENCES author (id),
title TEXT NOT NULL,
genre genre NOT NULL,
price NUMERIC(10, 2) NOT NULL CHECK (price >= 0),
published_on DATE NOT NULL,
stock INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX book_author_idx ON book (author_id);
The second migration is deliberately a later change, so that the post can show what a schema change does to compiled code. It adds a mandatory isbn column (V2__book_isbn.sql):
ALTER TABLE book ADD COLUMN isbn TEXT;
UPDATE book SET isbn = 'legacy-' || id WHERE isbn IS NULL;
ALTER TABLE book ALTER COLUMN isbn SET NOT NULL;
ALTER TABLE book ADD CONSTRAINT book_isbn_key UNIQUE (isbn);
Why Flyway and jOOQ belong together. The migrations are the one place the schema is written by hand. jOOQ generates from the database those migrations built, so there is no second description of the schema to keep in sync, and noCREATE TABLEhidden in a test fixture. The application itself runs the same migrations at startup (spring.flyway.locationsin application.properties), so the database a test sees is the database the generated code was made from.
Reference: the full code generator configuration (Maven profile)
The generator is configured in a Maven profile called codegen in pom.xml, so an ordinary mvn test never needs a database for it. It first runs flyway:migrate against a throwaway PostgreSQL, then jooq-codegen:generate against the same database:
<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<version>${jooq.version}</version>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
</dependencies>
<configuration>
<jdbc>
<url>${codegen.jdbc.url}</url>
<user>bookshop</user>
<password>bookshop</password>
</jdbc>
<generator>
<database>
<name>org.jooq.meta.postgres.PostgresDatabase</name>
<inputSchema>public</inputSchema>
<excludes>flyway_schema_history</excludes>
</database>
<generate>
<pojos>true</pojos>
<pojosAsJavaRecordClasses>true</pojosAsJavaRecordClasses>
<daos>false</daos>
<generatedAnnotation>false</generatedAnnotation>
<deprecated>false</deprecated>
</generate>
<target>
<packageName>com.ankurm.jooq.generated</packageName>
<directory>src/main/java</directory>
</target>
</generator>
</configuration>
</plugin>
Choices that matter: pojosAsJavaRecordClasses makes the generated POJOs Java records, daos is off because the repository classes here are written by hand, generatedAnnotation is off so the output does not carry a timestamp that would make every regeneration a noisy diff, and flyway_schema_history is excluded so Flyway’s own bookkeeping table does not become a Java class.
Going deeper
- Flyway PostgreSQL support note: Flyway documentation
- Boot reference for SQL databases, jOOQ and Flyway
- Boot 4.2 changes in general: Spring Boot 4.2 GA: What’s New and the 4.1 to 4.2 Upgrade Checklist
Generate the code, and see what comes out
Code generation is one script: start a throwaway PostgreSQL in Docker, apply the migrations, run the generator, remove the container. It is codegen.sh. The run, captured by run-all.sh, is in 00-codegen-run.txt:generated files:
src/main/java/com/ankurm/jooq/generated/DefaultCatalog.java
src/main/java/com/ankurm/jooq/generated/Indexes.java
src/main/java/com/ankurm/jooq/generated/Keys.java
src/main/java/com/ankurm/jooq/generated/Public.java
src/main/java/com/ankurm/jooq/generated/Tables.java
src/main/java/com/ankurm/jooq/generated/enums/Genre.java
src/main/java/com/ankurm/jooq/generated/tables/Author.java
src/main/java/com/ankurm/jooq/generated/tables/Book.java
src/main/java/com/ankurm/jooq/generated/tables/Review.java
src/main/java/com/ankurm/jooq/generated/tables/pojos/Author.java
src/main/java/com/ankurm/jooq/generated/tables/pojos/Book.java
src/main/java/com/ankurm/jooq/generated/tables/pojos/Review.java
src/main/java/com/ankurm/jooq/generated/tables/records/AuthorRecord.java
src/main/java/com/ankurm/jooq/generated/tables/records/BookRecord.java
src/main/java/com/ankurm/jooq/generated/tables/records/ReviewRecord.java
checksum of generated sources before: 2b5f174e286873e9
checksum of generated sources after: 2b5f174e286873e9
Fifteen files. The checksum lines show that regenerating over the committed copy produced the same bytes, so generation is deterministic and a regeneration only shows up in a diff when the schema really changed. The interesting one is the table class. This is the part of Book.java that declares the columns:
public final TableField<BookRecord, Long> ID = createField(DSL.name("id"), SQLDataType.BIGINT.nullable(false).generatedAlwaysAsIdentity(), this, "");
public final TableField<BookRecord, Long> AUTHOR_ID = createField(DSL.name("author_id"), SQLDataType.BIGINT.nullable(false), this, "");
public final TableField<BookRecord, String> TITLE = createField(DSL.name("title"), SQLDataType.CLOB.nullable(false), this, "");
public final TableField<BookRecord, Genre> GENRE = createField(DSL.name("genre"), SQLDataType.VARCHAR.nullable(false).asEnumDataType(Genre.class), this, "");
public final TableField<BookRecord, BigDecimal> PRICE = createField(DSL.name("price"), SQLDataType.NUMERIC(10, 2).nullable(false), this, "");
public final TableField<BookRecord, LocalDate> PUBLISHED_ON = createField(DSL.name("published_on"), SQLDataType.LOCALDATE.nullable(false), this, "");
public final TableField<BookRecord, Integer> STOCK = createField(DSL.name("stock"), SQLDataType.INTEGER.nullable(false).defaultValue(DSL.field(DSL.raw("0"), SQLDataType.INTEGER)), this, "");
public final TableField<BookRecord, String> ISBN = createField(DSL.name("isbn"), SQLDataType.CLOB.nullable(false), this, "");
Every column is a field with a Java type: NUMERIC(10, 2) became BigDecimal, DATE became LocalDate, the PostgreSQL enum became a generated Java enum Genre, and the identity column carries generatedAlwaysAsIdentity(). Next to it jOOQ wrote a POJO. Because of the pojosAsJavaRecordClasses switch it is a Java record, so the result of a query can already be an immutable value with accessors (pojos/Book.java):
public record Book(
Long id,
Long authorId,
String title,
Genre genre,
BigDecimal price,
LocalDate publishedOn,
Integer stock,
String isbn
) implements Serializable {
private static final long serialVersionUID = 1L;
public Book(Book value) {
this(
value.id,
value.authorId,
value.title,
value.genre,
value.price,
value.publishedOn,
value.stock,
value.isbn
);
Commit the generated code, or generate it in every build? This module commits it, for three reasons: a schema change then shows up as a readable diff in code review, the project builds with no database and no Docker for plain compilation, and the drift test described next fails the build if the committed copy goes stale. The alternative, generating during mvn generate-sources against a Testcontainers or Docker database, keeps the repository smaller but makes every build, including the one on a laptop with no Docker running, depend on a live database. Both are legitimate; pick one on purpose.
Going deeper
- The generator command and container handling: codegen.sh
- jOOQ manual, code generation
- Native PostgreSQL enums and their JPA counterpart: Enum Mapping in Hibernate 7
Let the compiler guard the schema
Now the payoff. The module’s real code, which usesBOOK.ISBN, is left alone and three things are broken on purpose in a throwaway copy by compile-errors.sh. The compiler’s own messages are in 10-compile-errors.txt:
== A. wrong type: BOOK.PRICE.eq("12.50") ==
src/main/java/com/ankurm/jooq/WrongType.java:[10,53] no suitable method found for eq(java.lang.String)
method org.jooq.Field.eq(java.math.BigDecimal) is not applicable
(argument mismatch; java.lang.String cannot be converted to java.math.BigDecimal)
method org.jooq.Field.eq(org.jooq.Select<? extends org.jooq.Record1<java.math.BigDecimal>>) is not applicable
(argument mismatch; java.lang.String cannot be converted to org.jooq.Select<? extends org.jooq.Record1<java.math.BigDecimal>>)
method org.jooq.Field.eq(org.jooq.Field<java.math.BigDecimal>) is not applicable
(argument mismatch; java.lang.String cannot be converted to org.jooq.Field<java.math.BigDecimal>)
method org.jooq.Field.eq(org.jooq.QuantifiedSelect<? extends org.jooq.Record1<java.math.BigDecimal>>) is not applicable
(argument mismatch; java.lang.String cannot be converted to org.jooq.QuantifiedSelect<? extends org.jooq.Record1<java.math.BigDecimal>>)
== B. typo: BOOK.ISBNN ==
src/main/java/com/ankurm/jooq/Typo.java:[10,31] cannot find symbol
symbol: variable ISBNN
location: variable BOOK of type com.ankurm.jooq.generated.tables.Book
== C. regenerate from schema version 1 only (no isbn column), compile the unchanged application ==
src/main/java/com/ankurm/jooq/BookshopRepository.java:[49,26] cannot find symbol
symbol: variable ISBN
location: variable BOOK of type com.ankurm.jooq.generated.tables.Book
src/main/java/com/ankurm/jooq/BookshopRepository.java:[131,33] cannot find symbol
symbol: variable ISBN
location: variable BOOK of type com.ankurm.jooq.generated.tables.Book
src/main/java/com/ankurm/jooq/BookshopRepository.java:[130,26] cannot find symbol
symbol: variable ISBN
location: variable BOOK of type com.ankurm.jooq.generated.tables.Book
Case A is a wrong type: BOOK.PRICE is a Field<BigDecimal>, so comparing it with a String has no matching eq overload. Case B is the typo. Case C is the one that matters in a real project: the application is compiled against classes regenerated from schema version 1, where the isbn column does not exist yet, and every place that uses it is reported with a file and line. Imagine the same exercise after a teammate drops or renames a column in a migration. The broken sources are in src/broken/, outside the build, so they cannot break it for real.
There is one gap, and the module closes it with a test. If someone adds a migration and forgets to regenerate, the old generated classes still compile, and the code simply does not know about the new column. CodegenDriftTest.java regenerates into a temporary directory from the database Flyway just migrated, and compares every file with the committed copy. When they match (01-codegen-drift-check.txt):
files regenerated from the live schema: 15
files committed in src/main/java: 15
byte-identical files: 15
verdict: committed generated code matches Flyway V1 + V2
And when a migration V3 adds a column and nobody regenerates, produced by drift-demo.sh on a throwaway copy (11-drift-detected.txt):
added src/main/resources/db/migration/V3__book_subtitle.sql, did NOT regenerate
org.opentest4j.AssertionFailedError: generated code is stale, run scripts/codegen.sh. Differing files: [tables/Book.java, tables/pojos/Book.java, tables/records/BookRecord.java] ==> expected: <true> but was: <false>
The message names the three files that differ (the table class, the POJO and the record), which is exactly what a new column touches. That turns “did you remember to regenerate?” from a code-review question into a red build.
Reference: how the drift test works
The test uses the generator as a library instead of through Maven. It builds a org.jooq.meta.jaxb.Configuration that mirrors the Maven profile, points it at the Testcontainers database, writes into a temporary directory, then compares the two file trees. The core of it, from CodegenDriftTest.java:
Configuration cfg = new Configuration()
.withJdbc(new Jdbc()
.withDriver("org.postgresql.Driver")
.withUrl(postgres.getJdbcUrl())
.withUser(postgres.getUsername())
.withPassword(postgres.getPassword()))
.withGenerator(new Generator()
.withDatabase(new Database()
.withName("org.jooq.meta.postgres.PostgresDatabase")
.withInputSchema("public")
.withExcludes("flyway_schema_history"))
.withGenerate(new Generate()
.withPojos(true).withPojosAsJavaRecordClasses(true)
.withDaos(false).withGeneratedAnnotation(false).withDeprecated(false))
.withTarget(new Target()
.withPackageName("com.ankurm.jooq.generated")
.withDirectory(tmp.toString())));
GenerationTool.generate(cfg);
It needs jooq-codegen on the test classpath only. Keep the test configuration and the Maven profile in step, or the two will disagree about what “generated” means.
Going deeper
- The test and the scripts that broke things on purpose: CodegenDriftTest.java, compile-errors.sh, drift-demo.sh
- jOOQ manual, column expressions and typed fields
Your first typed queries: INSERT, RETURNING and a record back
ADSLContext is the object you build queries with, and Spring Boot creates one for you from the DataSource. Inject it, and every query reads like the SQL it produces. Here is an insert that asks PostgreSQL to hand the new row back in the same statement (RETURNING) and converts it into the generated record, from BookshopRepository.java:
public Book insertBook(long authorId, String title, Genre genre, String price, String publishedOn, int stock, String isbn) {
return dsl.insertInto(BOOK)
.set(BOOK.AUTHOR_ID, authorId)
.set(BOOK.TITLE, title)
.set(BOOK.GENRE, genre)
.set(BOOK.PRICE, new BigDecimal(price))
.set(BOOK.PUBLISHED_ON, java.time.LocalDate.parse(publishedOn))
.set(BOOK.STOCK, stock)
.set(BOOK.ISBN, isbn)
.returning()
.fetchSingle()
.into(Book.class); // generated record -> generated Java record POJO
}
The comment says it all: returning().fetchSingle() gives a generated BookRecord, and .into(Book.class) copies it into the generated Java record. Nothing was written to say how columns map to fields. What jOOQ actually sent to PostgreSQL, and what came back, is in 02-autoconfig-and-insert-returning.txt:
SQL: insert into "public"."book" ("author_id", "title", "genre", "price", "published_on", "stock", "isbn") values (?, ?, cast(? as "public"."genre"), ?, cast(? as date), ?, ?) returning "public"."book"."id", "public"."book"."author_id", "public"."book"."title", "public"."book"."genre", "public"."book"."price", "public"."book"."published_on", "public"."book"."stock", "public"."book"."isbn"
Returned POJO (a generated Java record): Book (7, 1, Returning Demo, TECH, 10.50, 2026-02-02, 1, 978-9-99)
One statement, one round trip: the id the database generated is already in the returned record. The generator also knows the id column is GENERATED ALWAYS AS IDENTITY, which PostgreSQL enforces if you try to set it yourself (same transcript, 02-autoconfig-and-insert-returning.txt):
insert with explicit id on GENERATED ALWAYS column: ERROR: cannot insert a non-DEFAULT value into column "id"
Intermediate: what Spring Boot configures for you, and two surprises in it
Spring Boot’s jOOQ auto-configuration builds a DefaultConfiguration from your DataSource and works out the SQL dialect (here POSTGRES). Reading spring-boot-jooq-4.2.0.jar with javap shows what else it wires: a SpringTransactionProvider so jOOQ uses Spring’s transaction manager, a connection provider over a TransactionAwareDataSourceProxy so jOOQ joins a running Spring transaction, and an exception-translating listener that turns jOOQ failures into Spring’s DataAccessException hierarchy. What the running context reported, from 02-autoconfig-and-insert-returning.txt:
DSLContext dialect: POSTGRES
listener providers on the DSLContext: 2
transaction provider: org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider
plain ExecuteListener bean calls so far: 0 (bean exists: true)
Surprise one: only ExecuteListenerProvider beans are registered. The auto-configuration collects ObjectProvider<ExecuteListenerProvider> (the javap output shows that parameter type). A bean that implements only ExecuteListener exists in the context and is never called. The last line above is that bean, IgnoredListener, with zero calls after a full seed run. The working logger, SqlLog.java, implements ExecuteListenerProvider as well. That cost one failed test run while writing this post: the SQL log came back empty, and nothing in the logs said why.
Surprise two: a dialect warning on PostgreSQL 17.12. jOOQ 3.21.9 logs this at startup (13-startup-log-lines.txt). Every statement in this post ran correctly on that database, so this is a log line to know about rather than a failure. I did not dig into which PostgreSQL version this jOOQ release treats as its newest, and the dialect enum has only POSTGRES, so there is no per-version dialect to pin:
o.j.i.D.logVersionSupport : Version mismatch : Database version is older than what dialect SQLDialect.POSTGRES supports: 17.12. Consider https://www.jooq.org/download/support-matrix to see what jOOQ version and edition supports which RDBMS versions.
Going deeper
- The logger and the ignored listener: SqlLog.java, IgnoredListener.java
- Boot reference, Using jOOQ
- Return-the-row-you-wrote queries as projections on the JPA side: Spring Data JPA Projections
Dynamic queries without string concatenation
Search screens have optional filters: a title fragment, a genre, a maximum price, an author’s country, any combination. With string SQL you end up gluingWHERE and AND together. With jOOQ every condition is an object, so you collect the ones that apply in a list and pass the list to where(). From BookshopRepository.java:
public List<BookRow> search(BookFilter f) {
List<Condition> conditions = new ArrayList<>();
if (f.titleContains() != null) conditions.add(BOOK.TITLE.containsIgnoreCase(f.titleContains()));
if (f.genre() != null) conditions.add(BOOK.GENRE.eq(f.genre()));
if (f.maxPrice() != null) conditions.add(BOOK.PRICE.le(f.maxPrice()));
if (f.authorCountry() != null) conditions.add(AUTHOR.COUNTRY.eq(f.authorCountry()));
return dsl.select(BOOK.TITLE, AUTHOR.NAME, BOOK.GENRE, BOOK.PRICE)
.from(BOOK)
.join(AUTHOR).on(AUTHOR.ID.eq(BOOK.AUTHOR_ID))
.where(conditions) // an empty list renders no WHERE at all
.orderBy(BOOK.TITLE)
.fetch(Records.mapping(BookRow::new));
}
The result type BookRow is a plain record declared in Views.java, with no annotations: Records.mapping(BookRow::new) hands the four selected columns to its constructor, in order, and the compiler checks that the four types fit. The same method called with no filters, then with one, then with all four, produced these statements (03-dynamic-where.txt), shown for the first and the last call:
SQL: select "public"."book"."title", "public"."author"."name", "public"."book"."genre", "public"."book"."price" from "public"."book" join "public"."author" on "public"."author"."id" = "public"."book"."author_id" order by "public"."book"."title"
SQL: select "public"."book"."title", "public"."author"."name", "public"."book"."genre", "public"."book"."price" from "public"."book" join "public"."author" on "public"."author"."id" = "public"."book"."author_id" where (lower("public"."book"."title") like ('%' || replace(replace(replace(lower(?), '!', '!!'), '%', '!%'), '_', '!_') || '%') escape '!' and "public"."book"."genre" = cast(? as "public"."genre") and "public"."book"."price" <= ? and "public"."author"."country" = ?) order by "public"."book"."title"
row: BookRow[title=Kata of Clean Code, author=Kenji Tanaka, genre=TECH, price=39.90]
An empty list renders no WHERE at all (the first statement), and with four filters the conditions are combined with and and every value is still a bind parameter (?), never pasted into the SQL. containsIgnoreCase turned into a like with the % and _ characters in the search term escaped, which a hand-built string usually forgets to do.
Going deeper
- The method and its record types: BookshopRepository.java, Views.java
- All three statements: 03-dynamic-where.txt
- jOOQ manual, conditional expressions
A parent with its children in one statement: MULTISET
The classic way to load a book with its reviews is a join, and a join repeats the book once per review. jOOQ’smultiset builds the nested collection inside the database and returns it as part of one row. From BookshopRepository.java:
public List<BookWithReviews> booksWithReviews() {
return dsl.select(
BOOK.TITLE,
multiset(select(REVIEW.RATING, REVIEW.BODY)
.from(REVIEW)
.where(REVIEW.BOOK_ID.eq(BOOK.ID))
.orderBy(REVIEW.ID))
.convertFrom(r -> r.map(Records.mapping(ReviewView::new))))
.from(BOOK)
.orderBy(BOOK.TITLE)
.fetch(Records.mapping(BookWithReviews::new));
}
One query, typed all the way down: the inner select becomes a List<ReviewView> and the outer one a List<BookWithReviews>. What it sent, what it returned, and the comparison with the flat join, from 04-multiset.txt:
statements sent: 1
SQL: select "public"."book"."title", (select coalesce(jsonb_agg(jsonb_build_array(t."v0", t."v1")), jsonb_build_array()) from (select "public"."review"."rating" as "v0", "public"."review"."body" as "v1" from "public"."review" where "public"."review"."book_id" = "public"."book"."id" order by "public"."review"."id") as t) from "public"."book" order by "public"."book"."title"
BookWithReviews[title=Compilers for Humans, reviews=[ReviewView[rating=5, body=Changed how I think], ReviewView[rating=4, body=Great examples], ReviewView[rating=5, body=Buy it]]]
BookWithReviews[title=Debugging a Moth, reviews=[]]
...
flat LEFT JOIN returns 9 rows for 6 books; MULTISET returns 6 rows
One statement was sent (the first line), the books come back with the right reviews nested inside, and a book with no reviews gets an empty list instead of disappearing. On PostgreSQL jOOQ builds the nesting with jsonb_agg in a correlated subquery, which you can read in the captured SQL. The flat join over the same data returns 9 rows for 6 books, which is the multiplication multiset avoids.
Intermediate: how this differs from fetch joins and N+1 in JPA
With JPA the same page of books-with-reviews is a decision: lazy loading triggers one extra query per book (the N+1 problem), a join fetch repeats parent rows and interacts badly with paging, and an entity graph is another thing to configure. multiset has no such decision to make. The cost is that you write the nested select yourself and get records, not managed entities, so there is nothing to modify and save back. Use it for read models.
Going deeper
- The captured nesting SQL and rows: 04-multiset.txt
- This blog: Catch N+1 Queries Automatically in Hibernate 7 measures the N+1 side of this comparison
- jOOQ manual, MULTISET value constructor
The queries that usually push people out of JPA: CTE, window function, upsert, seek
Some questions are natural in SQL and awkward in an object model: “the best-rated book in each genre”, “insert this row, or add to its stock if it already exists”, “the next page after id 3”. Each is one short jOOQ method here. First the ranking, a common table expression plus therank() window function, whose generated SQL and result are in 05-cte-window.txt:
public List<GenreLeader> topRatedPerGenre() {
var ratings = name("ratings").as(
select(BOOK.GENRE, BOOK.TITLE, avg(REVIEW.RATING.cast(Double.class)).as("avg_rating"))
.from(BOOK).join(REVIEW).on(REVIEW.BOOK_ID.eq(BOOK.ID))
.groupBy(BOOK.GENRE, BOOK.TITLE));
var genre = ratings.field(BOOK.GENRE);
var title = ratings.field(BOOK.TITLE);
var avgRating = ratings.field("avg_rating", Double.class);
var rank = rank().over(partitionBy(genre).orderBy(avgRating.desc(), title)).as("rnk");
var ranked = name("ranked").as(select(genre, title, avgRating, rank).from(ratings));
return dsl.with(ratings).with(ranked)
.select(ranked.field(genre), ranked.field(title), ranked.field(avgRating), ranked.field(rank))
.from(ranked)
.where(ranked.field(rank).eq(1))
.orderBy(ranked.field(genre))
.fetch(Records.mapping(GenreLeader::new));
}
GenreLeader[genre=FICTION, title=Poetical Science, avgRating=3.0, rank=1]
GenreLeader[genre=SCIENCE, title=Notes on the Analytical Engine, avgRating=4.5, rank=1]
GenreLeader[genre=HISTORY, title=Tokyo Trains, avgRating=4.0, rank=1]
GenreLeader[genre=TECH, title=Compilers for Humans, avgRating=4.666666666666667, rank=1]
The method returns a GenreLeader record per genre. The full rendered statement, with both CTEs, is in the transcript; I left it out of the page because the Java above is the readable version of it, which is the point. Tie-breaking is explicit here (title after the average), because without it two books with the same average would both rank 1.
The upsert is INSERT ... ON CONFLICT (isbn) DO UPDATE. Calling it twice with the same ISBN inserts once and then adds to the stock, and returns the same row id both times (06-upsert-and-keyset.txt):
.onConflict(BOOK.ISBN)
.doUpdate()
.set(BOOK.STOCK, BOOK.STOCK.plus(stock))
.returning()
.fetchSingle()
.into(Book.class);
first call -> stock 4 (inserted)
second call -> stock 8 (conflict, stock added); same id: true
Last, keyset pagination (also called seek): ask for the rows after the last id you saw, not for page number N. seek() adds the where id > ? for you (from BookshopRepository.java, output in 06-upsert-and-keyset.txt):
public KeysetPage pageAfter(Long afterId, int size) {
List<Long> ids = dsl.select(BOOK.ID).from(BOOK)
.orderBy(BOOK.ID)
.seek(afterId == null ? 0L : afterId)
.limit(size)
.fetch(BOOK.ID);
return new KeysetPage(ids, ids.size() == size ? ids.getLast() : null);
}
page 1 SQL: select "public"."book"."id" from "public"."book" where "public"."book"."id" > ? order by "public"."book"."id" fetch next ? rows only
page 1: [1, 2, 3] next=3
page 2 SQL: select "public"."book"."id" from "public"."book" where "public"."book"."id" > ? order by "public"."book"."id" fetch next ? rows only
page 2: [4, 5, 6] next=6
Page two starts exactly where page one ended, and the SQL has no offset, so the database does not have to read and throw away the first N rows. Why that matters, and how Spring Data JPA does the same with its Window API, is the subject of Spring Data JPA Pagination and Sorting.
A fair comparison, not a win for one side. Hibernate 6.2 and later can express common table expressions and window functions in HQL (see the Hibernate team’s Hibernate ORM 6.2 CTE announcement and Vlad Mihalcea on window functions in HQL), and I did not rerun these queries in HQL for this post. What jOOQ adds is not “JPA cannot” but that the whole statement is typed against the real schema, the database features you use are the database’s own (jsonb_agg,ON CONFLICT,RETURNING), and you can read the SQL you will get.
Going deeper
- All three methods: BookshopRepository.java
- Transcripts: 05-cte-window.txt, 06-upsert-and-keyset.txt
- The offset-versus-keyset trade-off, measured: Spring Data JPA Pagination and Sorting: Page vs Slice vs Keyset Scrolling
Transactions: jOOQ borrows Spring’s, and two defaults still bite
jOOQ does not run its own transaction machinery under Spring Boot. It uses Spring’s, so@Transactional works on code that uses a DSLContext exactly as it does for JDBC or JPA. TransactionTests.java runs six scenarios, each against a real database, and asserts the outcome. The transcript is 08-transactions.txt:
seeded authors: 3
1. no @Transactional, exception after 2 inserts -> author persisted: true, book persisted: true
2. @Transactional, RuntimeException -> author persisted: false, book persisted: false
3. @Transactional, checked IOException -> author persisted: true, book persisted: true
4. @Transactional(rollbackFor=Exception.class) -> author persisted: false, book persisted: false
5. dsl.transaction inside @Transactional, inner fails, caught -> caught inner failure, outer continues (author id 8)
outer author persisted: true, inner author persisted: false
6. dsl.transaction alone: success persisted: true; failure persisted: false
Read it row by row. Case 1 is the easy one to forget: with no @Transactional, each statement commits on its own, so an exception after two inserts leaves both behind. Case 2 is the normal rollback. Case 3 is the Spring default that surprises people: a checked exception (IOException) does not roll back, and the data is committed. Case 4 fixes it with rollbackFor. These four are Spring behaviour, and jOOQ simply inherits them. The code for cases 1 to 4 is in StockService.java.
Cases 5 and 6 are about jOOQ’s own dsl.transaction(...) block. Inside a running @Transactional method it becomes a nested unit of work, and when it fails and the exception is caught the outer transaction survives:
outer author persisted: true, inner author persisted: false). The mechanism, read from the jar: SpringTransactionProvider.begin creates a DefaultTransactionDefinition with the constant 6, which is PROPAGATION_NESTED (confirmed with javap -c on spring-boot-jooq-4.2.0.jar), and Spring’s JDBC transaction manager implements nested transactions with savepoints. I did not capture the SAVEPOINT statements themselves, so that last step rests on Spring’s documented behaviour plus the observed outcome. Case 6 shows dsl.transaction on its own, with no surrounding @Transactional: it commits on success and rolls back on failure. The code, from StockService.java:
public String nestedTransactionSavepoint() {
long a = repo.insertAuthor("Outer Author", "US");
try {
dsl.transaction(cfg -> {
cfg.dsl().insertInto(AUTHOR).set(AUTHOR.NAME, "Inner Author").set(AUTHOR.COUNTRY, "US").execute();
throw new IllegalStateException("inner block fails");
});
} catch (IllegalStateException e) {
return "caught inner failure, outer continues (author id " + a + ")";
}
return "unreachable";
}
Intermediate: mixing jOOQ and JPA in one transaction
Because both use the same Spring PlatformTransactionManager and the same DataSource, a @Transactional method can save an entity through Spring Data JPA and run a jOOQ report in the same transaction. Two things to remember: Hibernate buffers writes until flush, so a jOOQ query in the same method may not see an entity you just saved unless you flush first, and jOOQ never sees or updates entities in the persistence context. This module does not include JPA, so I did not run that combination; treat it as the expected behaviour of the two libraries rather than as something this post demonstrated.
Going deeper
- The service and the six-scenario test: StockService.java, TransactionTests.java
- Spring Framework reference, transaction management (rollback rules and propagation)
Test against the real database with Testcontainers
Every number in this post comes from tests that run against a real PostgreSQL 17, because jOOQ’s value is the SQL it sends, and an in-memory fake database would test a different dialect. Testcontainers startspostgres:17-alpine in Docker, and Spring Boot’s @ServiceConnection points the DataSource at it. Flyway then migrates it when the Spring context starts. The base class every test extends, from PostgresTestBase.java:
@SpringBootTest
abstract class PostgresTestBase {
@ServiceConnection
static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");
static {
postgres.start();
}
The container is a started-once singleton, not the per-class @Container you see in most Testcontainers examples. That choice came from a real failure while building this module, reproduced on purpose by container-trap.sh. With a per-class @Container and two test classes, the first class passes. Spring caches the application context between classes, so the second class reuses a connection pool that still points at the container Testcontainers has already stopped (09-container-lifecycle-trap.txt, with the pool timeout shortened to 2 seconds so the failure is quick; the leading number on each line is how many times that line appeared, from uniq -c):
5 Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 2000ms (total=0, active=0, idle=0, waiting=0)
1 [ERROR] Tests run: 6, Failures: 0, Errors: 6, Skipped: 0, Time elapsed: 20.43 s <<< FAILURE! -- in com.ankurm.jooq.QueryTests
1 [ERROR] Tests run: 7, Failures: 0, Errors: 6, Skipped: 0
The fingerprint of this trap. The first test class is green and every test in the second class fails withNot everything needs the whole application. Spring Boot 4 has aConnection is not available, request timed outandtotal=0in the pool statistics, with nothing wrong in the test code. If it appears in your build, check whether astatic @Containeris declared per test class while the Spring context is shared.
@JooqTest slice (in org.springframework.boot.jooq.test.autoconfigure) that loads only the jOOQ and DataSource auto-configuration. JooqSliceTest.java shows what that includes and, more usefully, what it leaves out (12-jooqtest-slice.txt):
DSLContext present: true (dialect POSTGRES)
BookshopRepository in context: false
StockService in context: false
SqlLog in context: false
Flyway ran (schema has tables): true
author rows via typed API: 0
You get a working DSLContext and Flyway has already built the schema, but your own repository, service and listener beans are not there. Use the slice to test a query class you construct yourself, and the full @SpringBootTest for anything that needs your beans. The last line, author rows via typed API: 0, is correct: that slice has its own fresh container, so nothing was seeded into it.
Going deeper
- Base class, container choice and the slice test: PostgresTestBase.java, JooqSliceTest.java
- This blog: Spring Boot 4 Test Slices Compared for the other slices and the Boot 4 package moves
- Testcontainers PostgreSQL module (artifact
testcontainers-postgresqlin 2.x)
Should you use jOOQ at all?
Choose jOOQ when the SQL is where your difficulty lives. Reports, search screens with many optional filters, queries that use database features (window functions,jsonb,ON CONFLICT), read models that cut across tables, and teams that read SQL fluently and want the compiler on their side. Skip it, or keep it beside JPA instead of replacing it, when most of your code is create, read, update and delete on a model you own: you would write more code than Spring Data needs, and you give up change tracking, lazy loading and cascades. Know the costs before you start: a code generation step in the build, a regeneration discipline (the drift test in this post is the safety net), and a licence that depends on your database. The jOOQ Open Source Edition is Apache 2.0 and covers PostgreSQL, MySQL, MariaDB, H2, SQLite and a few others; Oracle and SQL Server need a commercial edition, according to the jOOQ download page (checked while writing this post; the page lists the open source edition’s databases “at their latest versions only”).
| Question | What this post showed |
|---|---|
| Does a wrong column or type fail early? | Yes, at javac, in all three cases of 10-compile-errors.txt; plain SQL strings do not (07). |
| Does a forgotten regeneration go unnoticed? | Not with the drift test (11-drift-detected.txt). |
| Can I get parent and children without N+1 or row multiplication? | Yes, with multiset: 1 statement, 6 books, versus 9 flat join rows (04). |
Does @Transactional work? | Yes, including a nested dsl.transaction, with Spring’s rules for checked exceptions (08). |
| Is there a persistence context? | No. Records are plain values; saving a change is an UPDATE you write. |
Further reading
- Companion module: spring-data-demo/jooq (source, scripts, and all fourteen transcripts under
output/); the module README has the output index: README.md - Spring Data JPA Pagination and Sorting: Page vs Slice vs Keyset Scrolling
- Spring Data JPA Projections: Interface, Record and Dynamic Projections
- JdbcClient in Spring Framework 7: Modern JDBC Without JPA
- MyBatis with Spring Boot 4: Mappers, Dynamic SQL and Pagination
- Jakarta Data with Hibernate vs Spring Data JPA
- Spring Boot 4 Test Slices Compared
- jOOQ manual
- jOOQ downloads and edition support
- Spring Boot reference: SQL databases
- Spring Boot 4.2.0 available now
- Hibernate ORM 6.2: common table expressions
No Comments yet!