skip to content

jOOQ

jOOQ generates Java or Kotlin classes from your schema and builds SQL in a typed DSL, so queries compile against real tables. It is the common JVM pick when a team writes SQL, not mapped objects.

on this pageshow

explore

questions

23

With jOOQ's code generator, which classes does it write for each table, and which outputs stay off unless you enable them?

level: juniorimportance: must knowfreq 50%

answer

  1. one class per table, one per row
  2. schema-wide constant holders
  3. records on, POJOs off
  4. DAOs pull in records and POJOs

basics

~20 s

For each table, jOOQ's code generator writes a table class with typed column fields and a record class for its rows, plus schema-wide Tables and Keys classes. POJOs, DAOs and interfaces are off by default.

solid answer

~30 s

For a `PAYMENT` table, jOOQ's default generator writes `tables.Payment`, a table class with a static `PAYMENT` instance and one typed `TableField` per column, and `tables.records.PaymentRecord`, which extends `UpdatableRecordImpl` when the table has a primary key and `TableRecordImpl` when it has none. Around them it writes schema-wide classes: `Tables`, `Keys`, `Indexes`, a schema class and `DefaultCatalog`. The `<generate>` flags for tables, records, keys, indexes, sequences and routines default to `true`; `pojos`, `daos`, `interfaces` and `immutablePojos` default to `false`. Turning on `daos` also turns on records and POJOs, because a generated DAO is built from both.

code

xml · 11 lines
xml
<generator>
  <name>org.jooq.codegen.DefaultGenerator</name>
  <generate>
    <pojos>true</pojos>
    <pojosAsJavaRecordClasses>true</pojosAsJavaRecordClasses>
    <daos>false</daos>
  </generate>
  <target>
    <packageName>com.example.payments.db</packageName>
  </target>
</generator>

go deeper

for a junior

Recall the two per-table outputs, the table class with typed fields and the record class, and that POJOs and DAOs must be switched on.

for a middle

Explain the schema-wide holders (Tables, Keys, DefaultCatalog), the default flags, and why enabling daos quietly turns on records and POJOs too.

for a senior

Show you can read generator output as a diagnostic: a keyed table whose record sits on TableRecordImpl means the schema source did not report its key.

for a principal

Weigh which outputs a codebase should allow: DAOs and POJOs add surface and coupling to tables, so a lead decides deliberately rather than enabling everything.

## What the code generator is **jOOQ's code generator** (the `jooq-codegen` module, run through `GenerationTool`, the Maven plugin `jooq-codegen-maven` or the Gradle plugin `org.jooq.jooq-codegen-gradle`) reads a schema from a **schema source**, builds an in-memory model of its tables, keys, sequences and routines, and writes Java or Kotlin source for that model. The default generator class is `org.jooq.codegen.DefaultGenerator`, which extends `JavaGenerator`; `org.jooq.codegen.KotlinGenerator` writes Kotlin instead. Output lands in the target package (default `org.jooq.generated`) under the target directory (default `target/generated-sources/jooq`, or `build/generated-sources/jooq` when the Gradle plugin fills it in). The generated classes are what make jOOQ queries compile against real tables: a renamed column becomes a compile error in every query that names it. ## What it writes for each table For a table `PAYMENT` in schema `PUBLIC`, the default naming strategy produces: - **The table class** `tables.Payment`: extends jOOQ's table implementation, holds a static singleton `PAYMENT`, and declares one `TableField<PaymentRecord, T>` per column, where `T` is the Java type the column maps to. - **The record class** `tables.records.PaymentRecord`: one instance holds one row. It extends `UpdatableRecordImpl` when the schema source reports a primary key and `TableRecordImpl` when it does not, so the record's abilities depend on what the source reported, not on what production holds. - **Optional extras per table**, only when enabled: a POJO `tables.pojos.Payment`, a DAO `tables.daos.PaymentDao` built on jOOQ's `DAOImpl`, and an interface `tables.interfaces.IPayment` that records and POJOs can share. ## What it writes once per schema Beside the per-table classes the generator writes holders that the rest of the code references: - `Tables`: a static reference to every table singleton, so `Tables.PAYMENT` works without importing each class. - `Keys`: primary, unique and foreign key constants, used by joins and by records that need their key. - `Indexes`: index constants, when `<indexes>` is on. - A **schema class** (for example `Public`) listing the schema's objects, and **`DefaultCatalog`** listing the schemas. - Sequence, routine and enum classes when the schema has them (a native enum type becomes a generated Java enum in an `enums` package). ## The `<generate>` flags and their defaults | Flag | Default | Writes | |---|---|---| | `tables` | `true` | table classes and `Tables` | | `records` | `true` | record classes | | `keys` | `true` | `Keys` | | `indexes` | `true` | `Indexes` | | `sequences`, `routines` | `true` | sequence and routine classes | | `relations` | `true` | key relationships between tables (forced on by tables or DAOs) | | `pojos` | `false` | plain value classes per table | | `immutablePojos` | `false` | POJOs with final fields | | `interfaces` | `false` | interfaces shared by records and POJOs | | `daos` | `false` | a DAO per table with a primary key | ## Flags that switch others on Some flags imply others, and the generator enforces the implication rather than failing: 1. `daos` implies **records** and **POJOs**: `AbstractGenerator.generateRecords()` returns true when DAOs are on, and so does `generatePojos()`. 2. `immutablePojos` implies **POJOs**. 3. **Relations** are forced on whenever tables or DAOs are generated: `generateRelations()` returns true if any of the three flags is set, so `<relations>false</relations>` alone changes nothing in a default run. 4. **Tables** are forced on whenever records or DAOs are generated, and when indexes are generated for a schema that has any, so `<tables>false</tables>` alone does not remove table classes. This is why a team that enables only `<daos>` still sees `pojos` and `records` packages appear. A DAO is skipped, with a log line, for any table that has no primary key. ## Java records and Kotlin data classes POJO style is configurable once `pojos` is on: - `pojosAsJavaRecordClasses` (default `false`) makes the Java generator write Java `record` types instead of mutable classes. - `pojosAsKotlinDataClasses` (default `true`) makes `KotlinGenerator` write `data class` POJOs. - `pojosEqualsAndHashCode` and `pojosToString` both default to `true`. ## What to say in an interview Name the two per-table outputs (table class and record class), the schema-wide holders, and the defaults: records on, POJOs and DAOs off. Mentioning that the record's base class depends on whether a primary key was found shows you know the generator is only as good as the schema it reads.

  • Why might a generated jOOQ record extend TableRecordImpl although the table has a primary key in production?
    The default strategy picks `UpdatableRecordImpl` only when the schema source it read reports a primary key. If that source did not show the key, for example because the object is a view, or the database or scripts the generator read lack the constraint, the record is written on `TableRecordImpl` and loses key-based update and refresh. Fix the source, then regenerate.
  • How do you get Java records or Kotlin data classes instead of mutable POJOs from jOOQ's generator?
    Enable `<pojos>` first. For the Java generator, set `<pojosAsJavaRecordClasses>true</pojosAsJavaRecordClasses>`. With `org.jooq.codegen.KotlinGenerator`, POJOs are already data classes, because `pojosAsKotlinDataClasses` defaults to true. For classic Java classes with final fields, `immutablePojos` is the switch, and it implies POJOs on its own.

  • jOOQ generates POJOs and DAOs for every table out of the box.
  • Every generated record is an UpdatableRecord, whether or not the table has a key.
  • The generator writes only table classes; record classes are written by hand.
  • Generated table classes expose column names as plain strings, not typed fields.
open as a page

In jOOQ, what is a DSLContext, and what does the SQLDialect you configure on it decide?

level: juniorimportance: must knowfreq 60%

basics

~20 s

DSLContext is jOOQ's entry point: it wraps a Configuration holding the connection source, the SQLDialect and the Settings, then builds and executes queries. The SQLDialect decides how each query renders as SQL for the target database.

open as a page

In jOOQ, how do you map fetched rows into your own POJOs, Java records or Kotlin data classes?

level: juniorimportance: must knowfreq 55%

basics

~10 s

Call fetchInto(Type.class) or Record.into(Type.class) to let jOOQ's DefaultRecordMapper map by name or constructor, or pass a RecordMapper such as Records.mapping(Type::new) to fetch() for a compiler-checked, positional mapping.

open as a page

In jOOQ, what do a Configuration and its ConnectionProvider do, and where does a DSLContext get its JDBC connection?

level: juniorimportance: must knowfreq 50%

basics

~20 s

A jOOQ Configuration bundles the SQLDialect, Settings, ConnectionProvider, TransactionProvider and listeners that a DSLContext runs on. Its ConnectionProvider hands out a JDBC Connection through acquire() once per statement execution and takes it back through release().

open as a page

Where can jOOQ's code generator read a schema from, a live database, DDLDatabase or LiquibaseDatabase, and what does each trade off?

level: middleimportance: must knowfreq 48%

basics

~20 s

jOOQ's code generator either reverse-engineers a running database over JDBC or simulates one: DDLDatabase parses SQL scripts and LiquibaseDatabase applies a changelog, both on in-memory H2. Simulation needs no server but can miss vendor-specific DDL.

open as a page

In jOOQ, how does a bind value differ from an inlined value, and when is inlining the right choice?

level: middleimportance: must knowfreq 55%

basics

~20 s

jOOQ binds by default: a value passed to eq() or DSL.val renders as a ? placeholder sent separately. DSL.inline writes an escaped literal into the SQL text. Inline only true constants; varying inlined values defeat statement and plan caching.

open as a page

When jOOQ's UpdatableRecord.store() runs, how does it decide between INSERT and UPDATE, and which columns does it write?

level: middleimportance: must knowfreq 50%

basics

~20 s

By default store() runs an UPDATE when the primary key is set and untouched since the fetch, and an INSERT when a key field is touched or a NOT NULL key is null; either statement writes only touched fields.

open as a page

With Spring Boot's jOOQ auto-configuration, an @Transactional order method writes rows and then calls dsl.transactionResult; do they share a connection, and what commits when?

level: seniorimportance: must knowfreq 52%

basics

~10 s

Yes, one connection: Boot's TransactionAwareDataSourceProxy hands jOOQ the connection Spring bound to the thread. transactionResult runs on SpringTransactionProvider with PROPAGATION_NESTED, so it becomes a savepoint, and only the outer @Transactional method commits.

open as a page

With jOOQ's code generator, how do you use forcedTypes to map a JSONB column and a varchar status column to your own types?

level: middleimportance: should knowfreq 45%

basics

~20 s

A forcedType names your userType plus a converter or binding, and regexes that select columns (includeExpression) and database types (includeTypes). The generator then types the column as your class, so records and queries carry it end to end.

open as a page

In jOOQ's code generator, how do the includes and excludes patterns decide what gets generated, for example to skip a migration history table?

level: middleimportance: should knowfreq 40%

basics

~20 s

jOOQ's includes and excludes are Java regular expressions matched against each object's whole name, qualified or not; excludes win over includes, and an empty includes means everything. Excluding flyway_schema_history keeps Flyway's history table out of the generated code.

open as a page

In jOOQ, how do you build a customer search query whose WHERE clause depends on which optional filters were supplied?

level: middleimportance: should knowfreq 50%

basics

~20 s

Build each supplied filter as a jOOQ Condition from a generated Field, then combine them with DSL.noCondition() or pass a List<Condition> to where(). Absent filters add nothing, values stay bound, and type errors fail at compile time.

open as a page

In jOOQ, how do batchStore and the Loader API differ when a service must write thousands of rows?

level: middleimportance: should knowfreq 30%

basics

~20 s

batchStore(records) applies store() rules to records already in memory and sends them as JDBC batches grouped by identical SQL; the Loader API, started with loadInto(table), imports CSV, JSON, XML, arrays or records with duplicate, error, bulk, batch and commit options.

open as a page

In jOOQ, how does MULTISET return each order with its order lines nested inside it in a single query?

level: middleimportance: should knowfreq 35%

basics

~20 s

DSL.multiset(subquery) turns a correlated subquery into a column of type Result<R>; jOOQ renders it as a nested collection the dialect supports, usually JSON or XML, decodes it, and convertFrom maps the inner rows into a list.

open as a page

What is jOOQ's ExecuteListener, and how do you add one to Spring Boot's DSLContext without dropping Boot's exception translation?

level: middleimportance: should knowfreq 34%

basics

~20 s

An ExecuteListener receives callbacks across every jOOQ statement's lifecycle, such as executeStart, executeEnd and exception. In Spring Boot, declare it as an ExecuteListenerProvider bean so Boot adds it beside its exception-translator listener; configuration.set(listener) would replace that translator.

open as a page

Outside Spring, how does jOOQ's DSLContext.transactionResult commit, roll back and nest, and why must the lambda use its Configuration argument?

level: middleimportance: should knowfreq 42%

basics

~20 s

Without Spring, transactionResult runs on jOOQ's DefaultTransactionProvider: one connection, auto-commit off, commit when the lambda returns, rollback on any Throwable, savepoints for nested calls. Statements must use the lambda's Configuration, or they run on a different connection.

open as a page

After upgrading jOOQ's Gradle codegen plugin, compilation fails on REQUIRE_RUNTIME_JOOQ_VERSION in the generated DefaultCatalog; what went wrong and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

jOOQ's generated catalog references a constant for the generator's minor release, such as Constants.VERSION_3_21, so it stops compiling when the runtime jar is an older minor. Align the plugin and runtime versions instead of disabling the check.

open as a page

A nightly jOOQ export of a few million rows exhausts the heap or leaks connections; which fetch method should it use, and what must it close?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Use fetchLazy() for a Cursor, or fetchStream(), inside try-with-resources, and set fetchSize so the driver does not buffer everything. fetch() and for-each loops materialise every row; an unclosed Cursor or Stream holds its statement, result set and connection.

open as a page

In jOOQ, when does a custom column type need a Binding rather than just a Converter, and what breaks if you choose wrongly?

level: seniorimportance: should knowfreq 32%

basics

~20 s

A Converter<T, U> maps a type JDBC already handles to your own type and back; a Binding<T, U> also controls the JDBC plumbing: bind-marker SQL, PreparedStatement set and result get. Use a Binding only when the driver or SQL needs it.

open as a page

For jOOQ's code generator on a payments service whose CI runners share no database, which schema source would you make the truth, and why?

level: principalimportance: should knowfreq 36%

basics

~20 s

Make the migrations the only truth and generate from a throwaway database of the production engine with them applied; DDLDatabase is a fallback for portable DDL when runners cannot host one. Avoid the deprecated LiquibaseDatabase.

open as a page

As the lead on a jOOQ codebase, what rule would you set for plain SQL templates such as DSL.field(String, Object...), and how would you enforce it?

level: principalimportance: should knowfreq 35%

basics

~10 s

Allow jOOQ plain SQL only as constant templates with bound or {n} arguments and an explicit DataType, inside a small reviewed module, and enforce it with jOOQ-checker's PlainSQLChecker plus @Allow.PlainSQL where it is permitted.

open as a page

As the lead of a jOOQ codebase, would you allow active-record writes through UpdatableRecord.store(), or require explicit INSERT and UPDATE statements?

level: principalimportance: should knowfreq 25%

basics

~20 s

Neither extreme suits every team: store() gives concise partial updates and opt-in optimistic locking, but hides the INSERT-or-UPDATE choice in key flags. A common rule allows it for fetch-edit-store of one row and requires explicit statements elsewhere.

open as a page

As the lead of a Spring Boot service using jOOQ, would you standardise on @Transactional or on dsl.transactionResult, and how would you enforce it?

level: principalimportance: should knowfreq 38%

basics

~20 s

Pick one model per codebase. In a Spring Boot service, @Transactional usually owns boundaries and transactionResult, which Boot turns into a nested savepoint, is allowed only as a deliberate savepoint step; enforce it with an architecture test and failure-path integration tests.

open as a page

How does jOOQ run a query reactively over R2DBC, and how does Kotlin coroutine code consume such a query?

level: middleimportance: nice to knowfreq 30%

basics

~10 s

jOOQ's ResultQuery implements the reactive-streams Publisher, so with a DSLContext built from an R2DBC ConnectionFactory, subscribing runs non-blocking. Kotlin code awaits it or turns it into a Flow through kotlinx-coroutines-reactive.

open as a page