[英]Returning id in generic insert using JOOQ
我有一个非常通用的 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();
}
有没有办法返回插入记录的id? 我的数据库中表的所有主键都命名为“id”,因此我可以对其进行 ahrdcode,但我找不到返回它并转换为 Integer/Long 的方法。 我正在使用 JOOQ 3.9.5。
编辑:我在下面使用 MSSQL。
写:
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);
}
这假设您使用的是生成的代码,其生成的Table
实例实现了Table.getIdentity()
。 或者,如果您无法提供身份,则可以编写:
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.