在executeInsert()之后的JOOQ,需要知道自动生成的ID

时间:2018-05-31 14:53:38

标签: java sql sqlite jooq

使用JOOQ(使用sqlite3)。

有一些看起来像这样的代码: (根据文档中的示例进行了修改:https://www.jooq.org/doc/latest/manual/sql-execution/fetching/pojos/

// 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?

此时,我需要知道数据库中自动生成的ID。

  • 关于如何获得它的任何想法?
  • 或者在保存之前是否需要设置ID?

1 个答案:

答案 0 :(得分:1)

使用executeInsert()似乎无法获取ID:

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

但是使用Record.store会:

book.store()

以下是如何从POJO转到Record,以便可以存储PJO,然后使用生成的ID获取更新的POJO:

// 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 (implicitly) using the BookRecord instead of create.executeInsert()
book.store();            // <--- THIS IS THE KEY DIFFERENCE

// Get new Book POJO from the BookRecord
MyBook newBook = book.into(MyBook.class);

// This is also a handy function to get the Record as Map, 
//   which is easier to view in the debugger
Map<String, Object> bookMap = book.intoMap();