[英]Returning id in generic insert using JOOQ
I have a very generic API to insert stuff using JOOQ to soem tables:我有一个非常通用的 API,可以使用 JOOQ 将内容插入到 soem 表中:
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?有没有办法返回插入记录的id? 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.
我的数据库中表的所有主键都命名为“id”,因此我可以对其进行 ahrdcode,但我找不到返回它并转换为 Integer/Long 的方法。 I'm using JOOQ 3.9.5.
我正在使用 JOOQ 3.9.5。
EDIT: I use MSSQL underneath.编辑:我在下面使用 MSSQL。
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()
.这假设您使用的是生成的代码,其生成的
Table
实例实现了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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.