Reputation: 50372
Using JOOQ (with sqlite3).
Have some code that looks like this: (Modified from example in the docs: 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?
At this point, I need to know the auto-generated ID from the database.
Upvotes: 2
Views: 1291
Reputation: 50372
Using executeInsert()
does not seem to get the ID back:
// Insert it (explicitly)
create.executeInsert(book);
However using Record.store
does:
book.store()
Here is how to go from POJO to Record so that the PJO can be stored and then get the updated POJO with the generted ID:
// 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();
Upvotes: 2