In jOOQ, how do you map fetched rows into your own POJOs, Java records or Kotlin data classes?
answer
- reflection versus a typed lambda
- fetchInto and into(Class)
- DefaultRecordMapper tries strategies in order
- Records.mapping with a constructor reference
- Java record constructor, position by default
basics
~10 sCall 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 sjOOQ 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 linesimport 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 defaultgo deeper
Recall the two routes: fetchInto or into(Class) for reflection, and fetch with Records.mapping and a constructor reference for typed mapping.
Explain DefaultRecordMapper's order of strategies: mutable POJO by name, Kotlin by parameter name, Java record by position by default, then MappingException.
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.
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.