When jOOQ's UpdatableRecord.store() runs, how does it decide between INSERT and UPDATE, and which columns does it write?
answer
- the primary key decides
- flags, not a database comparison
- only touched fields are written
- a setter call counts as a touch
- changed() deprecated since 3.20
basics
~20 sBy 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.
solid answer
~50 s`UpdatableRecord` is the generated record for a table with a primary or main unique key, and `store()` decides by looking at that key alone. If any key field is touched, or a NOT NULL key field is null, it runs an `INSERT`; if the key is set and untouched, which is the state of a freshly fetched record, it runs `UPDATE … WHERE id = ?`. Both statements carry only the fields whose touched flag is set, so database defaults still apply on insert and an update sends just the edited columns; a fetched record with nothing touched runs no statement and `store()` returns `0`. Calling a setter on a non-key field marks it touched even if the value is the same; `modified()` is the flag that compares with `original()`. `Record.changed()` is deprecated for removal since 3.20 in favour of `touched()`, and `Settings.recordDirtyTracking` (default `TOUCHED`) can switch to `MODIFIED` semantics.
code
java · 13 linesimport static com.example.backoffice.db.Tables.CUSTOMER;
import com.example.backoffice.db.tables.records.CustomerRecord;
import org.jooq.DSLContext;
CustomerRecord customer = dsl.fetchOne(CUSTOMER, CUSTOMER.ID.eq(42L));
customer.setEmail("[email protected]"); // EMAIL touched, ID untouched
customer.store(); // UPDATE customer SET email = ? WHERE id = ?
CustomerRecord fromForm = dsl.newRecord(CUSTOMER, form); // every field touched, ID included
fromForm.store(); // INSERT: duplicate key if customer 42 exists
dsl.executeUpdate(fromForm); // UPDATE customer SET ... WHERE id = 42go deeper
Recall that only generated records for keyed tables can store() themselves, and that a fetched record updates while a new one inserts.
Explain the key-flag rule, why only touched fields are written, how touched differs from modified, and that changed() is deprecated.
Diagnose the duplicate insert from a DTO-built record and name the fixes: fetch then edit, executeUpdate, or clearing the key's touched flag.
Weigh whether the implicit INSERT-or-UPDATE choice belongs in service code at all, and which Settings a team should fix for everyone.
## Three record types jOOQ's records form a small hierarchy; a `TableRecord` can insert itself, but only an `UpdatableRecord` can store, update, delete and refresh itself: | Type | What it represents | What it adds | |---|---|---| | `Record` | any row, including ad-hoc selects and joins | values, `original()`, `touched()` and `modified()` flags, mapping with `into(...)` | | `TableRecord` | a row of one table or view | `getTable()`, `insert()`, `fetchParent(...)` | | `UpdatableRecord` | a row of a table with a primary key or main unique key | `store()`, `update()`, `delete()`, `refresh()`, `merge()`, `copy()` | The code generator writes an `UpdatableRecord` subclass, such as `CustomerRecord`, for every table that has such a key. Records returned by `dsl.fetchOne(CUSTOMER, ...)` or created with `dsl.newRecord(CUSTOMER)` are **attached** to a `Configuration`, which is what lets `store()` reach the database. ## How store() picks the statement With the default `Settings`, `store()` runs this decision on the key fields: 1. If any primary key field is **touched**, run an `INSERT`. 2. If any NOT NULL primary key field is `null`, run an `INSERT` (a new record whose identity the database will assign). 3. Otherwise, run `UPDATE table SET … WHERE key = …`. It does **not** query the database to see whether the row exists, and it is not an upsert. A record you fetched and edited updates; a record you built yourself and filled, key included, inserts. Changing the key of a fetched record to a **different** value also inserts: jOOQ treats it as a request to copy the row under a new key, and marks every field touched so the copy is complete. Setting a fetched record's key to the value it already holds does not touch it. Only `Settings.updatablePrimaryKeys = true` (default `false`) lets a changed key turn into an `UPDATE` of the key column. ## Which columns go into the statement - The `INSERT` lists only touched fields, keys included, so columns you never set get their database `DEFAULT`. - The `UPDATE` sets only touched non-key fields and filters by the key values. - If an identity column exists, the generated value is fetched back into the record (`Settings.returnIdentityOnUpdatableRecord`, default `true`). - If version or timestamp fields are configured for optimistic locking, `store()` sets them on the statement too. - After a successful `store()`, `original()` equals the current values and all touched and modified flags are reset to `false`. - A fetched record with nothing touched runs no `UPDATE` (`Settings.updateUnchangedRecords` defaults to `NEVER`), and `store()` returns `0`. ## Touched, modified and the deprecated changed | Flag | Set when | Can you set it? | |---|---|---| | `touched()` | a setter was called on the field (for a fetched record's key, only when the value differs) | yes, `touched(boolean)` and per-field overloads | | `modified()` | the current value differs from `original()` | no, it is derived | | `changed()` | the pre-3.20 name for touched | deprecated for removal since 3.20 (#12494) | A record can be touched without being modified: `setName(currentName)` on a fetched record marks `NAME` touched, and the next `store()` writes it. If you would rather write only real changes, set `Settings.recordDirtyTracking` to `RecordDirtyTracking.MODIFIED`; the default is `TOUCHED`. Calling `touched(field, false)` clears a flag and also resets that field's `original()` to the current value. ## The duplicate-insert trap The most common production bug is a record built from incoming data. `dsl.newRecord(CUSTOMER, form)` copies every property from the form, including `id`, and marks every field touched. `store()` sees a touched key and runs an `INSERT`, which fails on the primary key or, without one on the input, creates a second customer. Fixes, in order of preference: - fetch the row by its key, copy the edited values onto it, then `store()`; - call `dsl.executeUpdate(record)`, which updates the row matching the record's key and writes its touched fields (optimistic-locking settings do not apply to it); - clear the key's flag with `record.touched(CUSTOMER.ID, false)` before `store()`, accepting that every other touched field is written. Two neighbours of `store()` are worth knowing. `refresh()` re-selects the row by key, overwrites the values and clears the flags, throwing `NoDataFoundException` if the row has gone. `copy()` returns an in-memory duplicate with the key reset and all fields touched, so storing the copy inserts a new row.
- How does store() take part in optimistic locking in jOOQ?Turn on `Settings.executeWithOptimisticLocking`, which is `false` by default. If the code generator marked version or timestamp columns (`recordVersionFields`, `recordTimestampFields`), `store()` adds their current values to the `UPDATE`'s `WHERE` clause and sets new ones; zero rows updated throws `DataChangedException`. Without such columns jOOQ first re-reads the row with `SELECT … FOR UPDATE` and compares it with the record's original values.
- What does refresh() do to an UpdatableRecord, and why call it after store()?`refresh()` re-selects the row by its key, overwrites the record's values, resets `original()` and clears the touched and modified flags; it throws `NoDataFoundException` if the row is gone. After an insert jOOQ already reads back an identity value, but columns filled by triggers or defaults are not returned unless `Settings.returnAllOnUpdatableRecord` is on, so `refresh()` is how you see them.
- Why does a record built with dsl.newRecord(CUSTOMER, form) insert a duplicate on store(), and how do you make it update?`newRecord(table, source)` marks every field touched, the key included, and a touched key makes `store()` choose `INSERT`. Fetch the row first and copy the edits onto it, call `dsl.executeUpdate(record)`, which updates the row with the record's key, or clear the key's flag with `record.touched(CUSTOMER.ID, false)`. Every other touched field is still written.
- store() compares each value with the database row to decide what to write
- store() runs an UPDATE whenever the record's ID field is non-null
- Calling a setter with the current value leaves that field out of the next store()
- Record.changed() is the current API for checking pending edits
- store() is an upsert that lets the database choose INSERT or UPDATE
- store() always writes every column of the table
Assumes jOOQ 3.21; Record.changed() and its overloads are deprecated for removal since 3.20 in favour of touched(), with modified() for real value changes.