skip to content

Records, Mapping & Batching

jOOQ hands rows back as Record objects that can be mapped into POJOs, Java records or data classes, and UpdatableRecord can write itself back. Interviewers ask how store() decides what to write.

on this pageshow

explore

questions

6

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

level: juniorimportance: must knowfreq 55%

answer

  1. reflection versus a typed lambda
  2. fetchInto and into(Class)
  3. DefaultRecordMapper tries strategies in order
  4. Records.mapping with a constructor reference
  5. Java record constructor, position by default

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.

solid answer

~40 s

jOOQ returns `Record` objects, and there are two ways to turn them into your types. `fetchInto(CustomerRow.class)` (or `record.into(CustomerRow.class)`) hands the work to `DefaultRecordMapper`, which reflects on the target: a mutable POJO with a no-argument constructor gets values by name (`CUSTOMER_NAME` lands on `setCustomerName` or a `customerName` field), a Kotlin data class gets them by constructor parameter name when `kotlin-reflect` is on the classpath, and a Java record goes through its canonical constructor **by position**, unless `Settings.mapRecordComponentParameterNames` is switched on. The typed alternative is `fetch(Records.mapping(CustomerRow::new))` on a typed `select(...)`: the compiler checks the number and types of the selected columns against the constructor. Many teams prefer it for anything that matters, because a dropped column or a changed type breaks the build instead of failing at run time.

code

java · 18 lines
java
import static com.example.backoffice.db.Tables.CUSTOMER;
import static org.jooq.Records.mapping;

import java.util.List;
import org.jooq.DSLContext;

public record CustomerRow(Long id, String name, String email) {}

List<CustomerRow> typed = dsl
    .select(CUSTOMER.ID, CUSTOMER.NAME, CUSTOMER.EMAIL)
    .from(CUSTOMER)
    .where(CUSTOMER.ACTIVE.isTrue())
    .fetch(mapping(CustomerRow::new));      // arity and types checked by the compiler

List<CustomerRow> reflective = dsl
    .select(CUSTOMER.ID, CUSTOMER.NAME, CUSTOMER.EMAIL)
    .from(CUSTOMER)
    .fetchInto(CustomerRow.class);          // canonical constructor, by position by default

go deeper

for a junior

Recall the two routes: fetchInto or into(Class) for reflection, and fetch with Records.mapping and a constructor reference for typed mapping.

for a middle

Explain DefaultRecordMapper's order of strategies: mutable POJO by name, Kotlin by parameter name, Java record by position by default, then MappingException.

for a senior

Show you have debugged a silent swap: same-typed columns reordered in a select, mapped positionally into a record, and how a typed mapper or a setting prevents it.

for a principal

Argue for a house style: typed mappers in production code, reflection where it is harmless, wrapper types everywhere, and a test that executes each query.

## What jOOQ hands back Every jOOQ query returns **records**: `Record` for an ad-hoc select, `Record3<Long, String, String>` when the select lists three typed columns, or a generated table record such as `CustomerRecord` when you select a whole table. Services rarely want to pass those around. They want their own types: a mutable **POJO**, a Java `record`, or a Kotlin `data class`. jOOQ offers two routes, and the difference between them is where mistakes are caught. ## Route 1: reflection with fetchInto and into(Class) `ResultQuery.fetchInto(Class)`, `Result.into(Class)` and `Record.into(Class)` all delegate to a `RecordMapper` obtained from the `RecordMapperProvider` in the `Configuration`. By default that is **`DefaultRecordMapper`**, which inspects the target class and tries a fixed list of strategies. In simplified order: 1. Arrays, and single-column results that a `ConverterProvider` can convert directly (a one-column select into `String` or `Long`). 2. Generated `TableRecord` types, matched by table field metadata. 3. A **mutable POJO** with a no-argument constructor: values are set by naming convention. A column `MY_field` is set through `MY_field(…)`, `myField(…)`, `setMY_field(…)`, `setMyField(…)`, or a non-final member called `MY_field` or `myField`. 4. A constructor annotated with `@ConstructorProperties`. 5. A Java `record`, by component name, but only when `Settings.mapRecordComponentParameterNames` is `true` (it defaults to `false`). 6. A Kotlin class, by constructor parameter name, when `kotlin-reflect` is available and `Settings.mapConstructorParameterNamesInKotlin` is on (the default). 7. A **matching constructor**, one with exactly as many parameters as the row has columns, filled **by index** unless `Settings.mapConstructorParameterNames` is on and parameter names are compiled in. If nothing applies, jOOQ throws a `MappingException` whose message lists every strategy it tried and why each failed, which is the fastest way to debug a mapping. ## Java records and Kotlin data classes | Target | Default path | What to watch | |---|---|---| | Mutable POJO | no-arg constructor plus setters or fields, by name | column aliases must match property names | | Java `record` | canonical constructor as a matching constructor, by position | select order must equal component order | | Kotlin `data class` | constructor parameter names via Kotlin reflection | needs `kotlin-reflect` on the classpath | | Generated `TableRecord` | table field metadata | excess or missing fields are ignored | The Java record row is the trap. Because name matching is off by default, `select(CUSTOMER.EMAIL, CUSTOMER.NAME)` into `record CustomerRow(String name, String email)` puts the email into `name`. Both are strings, so nothing fails. ## Route 2: a typed RecordMapper `RecordMapper<R, E>` is a functional interface with one method, `E map(R record)`. You can pass any lambda to `fetch(...)`, `Result.map(...)` or `fetchMap(...)`. The helper **`Records.mapping(...)`** adapts a constructor reference or a function of N arguments into a `RecordMapper` for a `RecordN`: - `select(CUSTOMER.ID, CUSTOMER.NAME, CUSTOMER.EMAIL)` produces `Record3<Long, String, String>`. - `fetch(Records.mapping(CustomerRow::new))` compiles only if `CustomerRow` has a constructor taking `(Long, String, String)`, in that order. - Adding, removing or retyping a column is a compile error at the query, not a runtime surprise. It still maps **by position**: two same-typed columns swapped in the select still compile. The gain is arity and type checking, not name checking. The same helper works from Kotlin with a data class constructor reference (`mapping(::CustomerRow)`), and it composes with nested results, so the same style carries over to one-to-many reads. ## Traps worth naming in an interview - **Primitive targets and NULL**: mapping a `NULL` into an `int` or `double` field sets `0` or `0.0`, so a null and a real zero become indistinguishable. Use wrapper types. - **Inner classes**: a non-static nested class cannot be instantiated reflectively; make it a top-level or static nested type. - **Runtime-only failures**: `fetchInto` problems surface as `MappingException` when the query runs, so a test that executes the query is the only guard. - **Computed columns need aliases**: name-based mapping only finds a property for `count(*)` or a concatenation if you give it a matching alias with `.as("orderCount")`; otherwise the value is silently dropped for a POJO, or must be matched by position for a constructor. - **Global customisation**: to plug in a different mapping strategy everywhere, supply your own `RecordMapperProvider` in the `Configuration` instead of wrapping every call. A reasonable house style: `Records.mapping` for typed selects in production code, `fetchInto` for quick scripts and for whole-table records, and wrapper types in every target class.

  • Why might fetchInto(CustomerRow.class) put the email into a Java record's name component without any error?
    With default settings, `DefaultRecordMapper` reaches a Java record through its matching constructor, one with as many parameters as the row has columns, and assigns values by index. If the select lists `EMAIL` before `NAME` and both are strings, the values swap silently. Keep the select order equal to the component order, enable `Settings.mapRecordComponentParameterNames`, or use `Records.mapping` and review the column order.
  • How do you change jOOQ's mapping behaviour for every fetchInto call at once?
    Supply your own `RecordMapperProvider` in the `Configuration`. jOOQ asks it for a `RecordMapper` for each record type and target class, so `fetchInto` and `into(Class)` use your strategy instead of `DefaultRecordMapper`. Delegate to `DefaultRecordMapper` for types you do not handle, and keep the provider cheap, since it runs for every mapped result.

  • fetchInto matches a Java record's components by name out of the box
  • Records.mapping checks column names against constructor parameter names
  • A NULL column mapped into an int field throws an exception
  • jOOQ cannot map by reflection, so every DTO needs a hand-written RecordMapper
  • A fetchInto mismatch is reported by the compiler

Assumes jOOQ 3.21, where Settings.mapRecordComponentParameterNames defaults to false and Java records map positionally unless it is enabled.

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

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

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

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