In jOOQ, how do batchStore and the Loader API differ when a service must write thousands of rows?
answer
- records in memory versus a source file
- store() rules, grouped by identical SQL
- loadInto(table), options, then a source
- duplicate, error, bulk, batch, commit
- defaults: error, abort, commitNone
basics
~20 sbatchStore(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.
solid answer
~40 s`dsl.batchStore(records).execute()` takes `UpdatableRecord`s you already hold and applies `store()` rules to each, so every record still becomes an `INSERT` or an `UPDATE` of its touched fields; with the default prepared statements, records that render the same SQL share a JDBC batch, so the mix of new and fetched records and their touched columns decides how many batches run. It is not an upsert. The Loader API imports a source: `dsl.loadInto(SUPPLIER_PRODUCT)`, then options such as `onDuplicateKeyIgnore()`, `onErrorIgnore()`, `bulkAfter(500)`, `batchAfter(10)` and `commitNone()`, then `loadCSV(file)`, `fields(...)` and `execute()`. The returned `Loader` reports `processed()`, `stored()`, `ignored()` and `errors()`. Its defaults are `onDuplicateKeyError()`, `onErrorAbort()`, `commitNone()` and no bulking or batching, and `commitNone()` is the documented choice when a surrounding transaction manager owns the commit.
code
java · 20 linesimport static com.example.backoffice.db.Tables.SUPPLIER_PRODUCT;
import com.example.backoffice.db.tables.records.SupplierProductRecord;
import java.io.File;
import org.jooq.DSLContext;
import org.jooq.Loader;
Loader<SupplierProductRecord> loader = dsl
.loadInto(SUPPLIER_PRODUCT)
.onDuplicateKeyIgnore()
.onErrorIgnore()
.bulkAfter(500)
.batchAfter(10)
.commitNone()
.loadCSV(new File("supplier-products.csv"))
.fields(SUPPLIER_PRODUCT.SKU, SUPPLIER_PRODUCT.NAME, SUPPLIER_PRODUCT.PRICE)
.execute();
int failed = loader.errors().size();
int stored = loader.stored();go deeper
Recall that batchStore writes records you hold in memory, while loadInto starts a Loader that imports a CSV, JSON or array source.
Explain how batchStore groups records by rendered SQL, and walk through the Loader's duplicate, error, bulk, batch and commit options with their defaults.
Show you can tune and debug an import: wrong ignored counts with batching, periodic commits that cannot roll back, and a headerless CSV losing its first row.
Decide who owns commits during large imports, how failed rows are reported back to the business, and when an import belongs in a set-based statement instead.
## Two tools for two shapes of work Why batching beats one statement per row is a general data-access topic; this answer covers the two jOOQ APIs that do it. | | `batchStore` | Loader API | |---|---|---| | Input | `UpdatableRecord`s you built or fetched | CSV, JSON, XML, arrays, records or streams | | Statement choice | `store()` semantics per record: `INSERT` or `UPDATE` | `INSERT`, with a duplicate-key policy | | Typical use | saving a set of edited or new aggregates | importing an external file into one table | | Result | `int[]` of update counts | a `Loader` with counts and `errors()` | ## batchStore: store() semantics in batches `DSLContext.batchStore(UpdatableRecord<?>...)` (and its `Collection` overload) returns a `Batch`; nothing runs until `execute()`. - Each record is judged exactly as `store()` would judge it: touched key or null NOT NULL key means `INSERT`, otherwise `UPDATE`, and only touched fields are written. - With the default `StatementType.PREPARED_STATEMENT`, jOOQ groups records whose rendered SQL is identical. The number of JDBC batches equals the number of distinct SQL strings; in the worst case that is one per record. - Record order is preserved as far as that grouping allows. The source's own example: `a1, a2, a3, b1, a4, c1, b3, a5`, where odd numbers insert and even numbers update, runs four batches: `INSERT a1, a3, a5`, `UPDATE a2, a4`, `INSERT b1, b3`, `INSERT c1`. - With `StatementType.STATIC_STATEMENT`, values are inlined, record order is kept entirely and jOOQ can send a single batch, at the price of losing bind values. - It is **not** an upsert: jOOQ, not the database, decides `INSERT` or `UPDATE`, based on each record's flags. - Siblings exist for a fixed statement type: `batchInsert`, `batchUpdate`, `batchMerge` and `batchDelete`. ## Choosing between them Reach for `batchStore` when the rows already exist as records because the service built or edited them, for example saving a reordered set of lines. Reach for the Loader when the rows come from outside, a supplier file, a JSON feed or an array of values, and you need a duplicate policy and per-row error reporting rather than an all-or-nothing exception. ## The Loader API step by step The Loader is a fluent builder that reads a source and inserts it into one table: 1. `dsl.loadInto(TABLE)` starts the load and returns the options step. 2. Options: duplicate handling, error handling, commit, batch and bulk sizes. 3. A source: `loadCSV(...)`, `loadJSON(...)`, `loadXML(...)`, `loadArrays(...)` or `loadRecords(...)`. 4. Field mapping: `fields(...)` lists target columns in source order (`null` skips a source column), or `fieldsCorresponding()` matches by name. 5. Source options such as `ignoreRows(int)`, `separator(char)` and `quote(char)` for CSV, then optional row listeners with `onRow(...)`. 6. `execute()`, which returns a `Loader` with `processed()`, `executed()`, `stored()`, `ignored()` and `errors()`. ## Options and their defaults | Group | Choices | Default | |---|---|---| | Duplicate keys | `onDuplicateKeyError()`, `onDuplicateKeyIgnore()`, `onDuplicateKeyUpdate()` | `onDuplicateKeyError()` | | Errors | `onErrorAbort()`, `onErrorIgnore()` | `onErrorAbort()` | | Commit | `commitNone()`, `commitEach()`, `commitAfter(int)`, `commitAll()` | `commitNone()` | | Batch | `batchNone()`, `batchAfter(int)`, `batchAll()` | `batchNone()` | | Bulk (multi-row `INSERT`) | `bulkNone()`, `bulkAfter(int)`, `bulkAll()` | `bulkNone()` | | CSV header rows | `ignoreRows(int)` | `1` | ## Traps - **Commit options and managed transactions**: `commitEach()`, `commitAfter(int)` and `commitAll()` commit and roll back directly on the connection from `Configuration.connectionProvider()`. The source warns this may not work with container-managed transactions or autocommit connections, and names `commitNone()` as the choice there. Who owns the transaction belongs to the runtime wiring, not to the Loader. - **No rollback with periodic commits**: with `commitEach()` or `commitAfter(int)`, an error never rolls back what was already committed, even under `onErrorAbort()`. Among the Loader's own commit options, only `commitAll()` rolls back the whole load on abort; with `commitNone()` the rollback is yours. - **Ignored counts with batching**: combining `onDuplicateKeyIgnore()` with `batchAll()` or `batchAfter(int)` can produce a wrong `ignored()` count on some dialects, because the driver cannot report it through a batch. - **onDuplicateKeyUpdate needs a unique key**: on a table without unique keys every row is inserted and it behaves like `onDuplicateKeyIgnore()`. - **Header rows**: CSV loads skip one row by default; a headerless file loses its first line unless you call `ignoreRows(0)`. - **Bulk or batch all**: `batchAll()` and `bulkAll()` force `commitAll()` if a periodic commit was configured.
- How many JDBC batches does jOOQ's batchStore send for a list mixing new and fetched-then-edited records?With prepared statements, jOOQ groups records whose rendered SQL is identical, so the count equals the number of distinct statements: one for the inserts of each table and touched-column set, one for each distinct update shape. Records that touched different columns render different `UPDATE`s and split into separate batches. `StatementType.STATIC_STATEMENT` inlines the values so jOOQ can send a single batch in record order.
- Why should a jOOQ Loader run with commitNone() inside an application-managed transaction?The Loader's other commit options call commit and rollback directly on the connection from `Configuration.connectionProvider()`, and the source warns this may not work with container-managed transactions or autocommit connections. With `commitNone()`, the default, the surrounding transaction decides, so a failed import can roll back together with the rest of the unit of work.
- batchStore lets the database decide INSERT or UPDATE, like an upsert
- batchStore always sends exactly one JDBC batch whatever the records look like
- The Loader API skips duplicate keys unless told otherwise
- The Loader commits after every batch by default
- loadCSV treats the first line as data unless you configure a header