You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JOOQ+SQLite执行executeInsert后如何获取自动生成ID?

How to Retrieve Auto-Generated ID After Insert with jOOQ + SQLite3

Question Context

Here's the code adapted from official docs for a jOOQ + SQLite3 development scenario:

// A "mutable" POJO class
public class MyBook {
    public int id;
    public String title;
}

// Create a new POJO instance
MyBook myBook = new MyBook();
// myBook.id = 10; <-- Id is NOT set here because the database auto-generates it
myBook.title = "Animal Farm";

// Load a jOOQ-generated BookRecord from your POJO
BookRecord book = create.newRecord(BOOK, myBook);

// Insert it (explicitly)
create.executeInsert(book);

// What is value of the auto-generated id?

After running executeInsert to complete the insertion, how can I get the auto-generated ID from SQLite? Do I need to manually set the ID before saving?


Answer

Let's break this down simply:

  1. You don't need to manually set the ID before saving
    SQLite's INTEGER PRIMARY KEY AUTOINCREMENT (or even just INTEGER PRIMARY KEY, which auto-increments by default) takes care of ID generation automatically. Manually setting the ID would either be ignored by the database (if it's configured to auto-generate) or lead to conflicts if that ID already exists in the table.

  2. Two straightforward ways to get the auto-generated ID

Option 1: Fetch from the existing BookRecord

jOOQ automatically populates the auto-generated ID back into your BookRecord object right after the insert finishes. As long as your jOOQ-generated BOOK table metadata marks the ID column as an auto-incrementing primary key (which it will if your SQLite table is defined correctly), you can grab the ID directly from the record:

create.executeInsert(book);
int generatedId = book.getId(); // Or use book.id if accessing the raw field directly

Option 2: Use returning() for explicit retrieval

For a more explicit approach (especially handy if you need to fetch multiple auto-generated fields), use jOOQ's returning() method with your insert statement. This returns the inserted record with all auto-populated fields:

BookRecord insertedBook = create.insertInto(BOOK)
                               .set(BOOK.TITLE, myBook.title)
                               .returning(BOOK.ID)
                               .fetchOne();

if (insertedBook != null) {
    int generatedId = insertedBook.getId();
}

Both methods work reliably with SQLite—just ensure your table's ID column is properly configured as an auto-incrementing primary key in your schema (e.g., id INTEGER PRIMARY KEY AUTOINCREMENT).


内容的提问来源于stack exchange,提问作者Chris Dutrow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:43:55