In jOOQ, how does MULTISET return each order with its order lines nested inside it in a single query?
answer
- a correlated subquery as a column
- Field<Result<R>> per parent row
- encoded as JSON, XML or native
- convertFrom with Records.mapping
- simplified emulation on some dialects
basics
~20 sDSL.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.
solid answer
~40 s`DSL.multiset(select(...).from(ORDER_LINE).where(ORDER_LINE.ORDER_ID.eq(ORDERS.ID)))` puts a correlated subquery into the select list as a `Field<Result<Record…>>`, so every order row carries its own lines. Few databases support `MULTISET` natively, so jOOQ emulates it: `Settings.emulateMultiset` defaults to `NestedCollectionEmulation.DEFAULT`, which picks the best encoding for the dialect (a JSON, JSONB or XML aggregation, or native support), and jOOQ decodes the payload back into typed records. Chaining `.convertFrom(r -> r.map(Records.mapping(OrderLine::new)))` turns the inner result into a `List<OrderLine>`, and `row(...).mapping(...)` does the same for a nested one-to-one value. The gain is one statement with no repeated parent columns and no hand-written grouping; the costs are a heavier plan, values that travel through an encoding, and a simplified emulation on dialects that cannot correlate derived tables.
code
java · 24 linesimport static com.example.backoffice.db.Tables.ORDERS;
import static com.example.backoffice.db.Tables.ORDER_LINE;
import static org.jooq.Records.mapping;
import static org.jooq.impl.DSL.multiset;
import static org.jooq.impl.DSL.select;
import java.util.List;
public record OrderLine(String sku, Integer quantity) {}
public record OrderView(Long id, String status, List<OrderLine> lines) {}
List<OrderView> orders = dsl
.select(
ORDERS.ID,
ORDERS.STATUS,
multiset(
select(ORDER_LINE.SKU, ORDER_LINE.QUANTITY)
.from(ORDER_LINE)
.where(ORDER_LINE.ORDER_ID.eq(ORDERS.ID))
.orderBy(ORDER_LINE.LINE_NO)
).convertFrom(r -> r.map(mapping(OrderLine::new))))
.from(ORDERS)
.where(ORDERS.CUSTOMER_ID.eq(customerId))
.fetch(mapping(OrderView::new));go deeper
Recall that DSL.multiset nests a subquery's rows inside each parent row, so one query returns orders with their lines.
Explain the encodings jOOQ picks through emulateMultiset, how convertFrom and Records.mapping produce typed lists, and row().mapping for one-to-one.
Name the limits you have met: simplified emulation on some dialects, large encoded payloads, ordering inside the subquery, and Bindings not applying to nested values.
Decide where nested reads replace hand-grouped joins, and how the team bounds payload size and checks plans for large parent sets.
## What MULTISET is for A back-office screen often needs orders together with their lines. A plain join returns one row per line and repeats every order column, and the application then has to group the flat rows back into a tree. jOOQ's `MULTISET` operator, from standard SQL, lets the query return the tree directly: each order row has a column whose value is a **nested result**, the list of its lines. In jOOQ, `DSL.multiset(TableLike<R>)` takes a subquery (any `Select` is a `TableLike`) and returns a `Field<Result<R>>`. When the subquery is **correlated**, filtering on the outer row as in `ORDER_LINE.ORDER_ID.eq(ORDERS.ID)`, each outer row gets only its own children. ## How jOOQ renders it Only a few dialects have a native `MULTISET`, so jOOQ emulates it. The choice is governed by `Settings.emulateMultiset`, an enum of type `NestedCollectionEmulation`: | Value | What jOOQ renders | |---|---| | `DEFAULT` | the best encoding for the current dialect, chosen transparently | | `JSON` | a JSON array aggregation of JSON objects, one per nested row | | `JSONB` | the same, using the binary JSON functions | | `XML` | an XML aggregation of XML elements | | `NATIVE` | the database's own nested-collection support, where it exists | The database computes the nested collection in the same statement, and jOOQ parses the encoded value back into a `Result` of typed records, applying the field data types and any `Converter` attached to the nested fields. The `@Support` annotation on `multiset` in jOOQ 3.21 lists open-source dialects such as PostgreSQL, MySQL, MariaDB, SQLite, H2 and DuckDB. ## Mapping the nested result into types A nested `Result` is rarely what the service wants. The usual steps are: 1. Write the child subquery with exactly the columns the child type needs, in constructor order. 2. Chain `.convertFrom(r -> r.map(Records.mapping(OrderLine::new)))` on the `multiset(...)` field. This is an **ad-hoc converter**: it turns `Result<Record2<String, Integer>>` into `List<OrderLine>` when results are read, and does not change the SQL. 3. Map the outer `Record3<Long, String, List<OrderLine>>` with `fetch(Records.mapping(OrderView::new))`. 4. Add `orderBy(...)` inside the subquery if line order matters, since a nested collection has no guaranteed order otherwise. For a nested **one-to-one** value, such as the customer's name and email on each order, use `DSL.row(CUSTOMER.NAME, CUSTOMER.EMAIL).mapping(CustomerRef::new)`, which yields a `SelectField<CustomerRef>` placed in the outer select. The result is a fully typed object graph from one round trip, built with the same compile-time checks as a flat typed select. ## Limits and traps - **Simplified emulation**: on dialects that cannot correlate derived tables, the source lists H2 and MariaDB among them, jOOQ uses a simplified emulation that does not support `SELECT DISTINCT`, aggregate functions, window functions, `GROUP BY`, `HAVING`, `LIMIT`, `OFFSET` or set operations inside the `MULTISET`. - **multisetAgg as the alternative**: `DSL.multisetAgg(...)` is an aggregate used with `GROUP BY` over a join, and the source notes it is not affected by that limitation. - **Bindings do not apply inside**: a custom `Binding` only governs JDBC interactions, so its logic does not run for values decoded from a nested collection; a `Converter` is applied recursively. - **Payload size**: every child row travels inside one encoded value per parent, so a parent with thousands of children produces a large value. Paginate the parents and keep child columns narrow. - **Plan cost**: a correlated subquery per parent still costs work in the database; check the plan for large parent sets as you would for any correlated subquery. ## When a flat select is still better - **Aggregates per parent**: if the screen needs only a line count or a total, a grouped select or a scalar subquery is smaller than shipping every child row. - **Very large child sets**: export-style reads of millions of child rows are better streamed flat than packed into one encoded value per parent. - **Writes**: `MULTISET` is a read construct; changes still go through explicit statements or records fetched for editing. Used with typed mapping, `MULTISET` replaces the join-then-group code that otherwise surrounds a one-to-many read, without leaving jOOQ's type checking.
- When would you reach for DSL.multisetAgg instead of DSL.multiset in jOOQ?`multisetAgg(...)` is an aggregate function: you join parent and child and `GROUP BY` the parent, and it collects the child columns into a nested result. jOOQ's documentation notes it is not affected by the simplified correlated-subquery emulation used on dialects such as H2 and MariaDB, so it helps there, or when the query is already a grouped join.
- Why can a custom jOOQ Binding fail to apply to values inside a MULTISET?The nested rows come back as one encoded value, JSON or XML for example, not as separate JDBC columns. jOOQ documents that a `Binding` applies only to JDBC interactions and does not influence how `multiset(...)` contents are mapped, so its `get(...)` logic is not applied to them. A `Converter` is applied recursively to `multiset(...)` and `row(...)` contents, so conversion that must also work in nested collections belongs in a `Converter`.
- jOOQ's MULTISET runs one extra query per parent row behind the scenes
- MULTISET in jOOQ works only on databases with a native MULTISET operator
- The nested lines arrive as raw JSON strings you must parse yourself
- Any subquery shape works inside MULTISET on every supported dialect
- A custom Binding converts values inside MULTISET just as it does for top-level columns