Reputation: 3311
I have a very generic API to insert stuff using JOOQ to soem tables:
void insert(@NonNull final Table<?> table,
@NonNull final Collection<Field<?>> columns,
@NonNull final Collection<Object> values) {
dslContext.insertInto(table)
.columns(columns)
.values(values)
.execute();
}
Is there a way to return id of that inserted record? All primary keys of tables in my db are named "id" so I could ahrdcode it but I cannot find a way to return it and cast to Integer / Long. I'm using JOOQ 3.9.5.
EDIT: I use MSSQL underneath.
Upvotes: 3
Views: 4285
Reputation: 221145
Write:
long insert(@NonNull final Table<?> table,
@NonNull final Collection<Field<?>> columns,
@NonNull final Collection<Object> values) {
return dslContext
.insertInto(table)
.columns(columns)
.values(values)
.returningResult(table.field("ID")) // Replace with your field name case
.fetchOne()
.into(long.class);
}
This assumes you're using generated code whose generated Table
instances implement Table.getIdentity()
. Alternatively, if you cannot provide an identity, you could write:
long insert(@NonNull final Table<?> table,
@NonNull final Collection<Field<?>> columns,
@NonNull final Collection<Object> values) {
dslContext
.insertInto(table)
.columns(columns)
.values(values)
.execute();
return dslContext.lastID().longValue();
}
Upvotes: 6