[英]How do I use Jooq insert ... returning in MySQL without code generation?
我一直在尝试在 MySQL 中使用基于 DSL 的表定义的 insert...returning(我没有使用代码生成),并且我返回的记录始终为空。 根据阅读,我需要在表定义中指定识别列,但我不知道如何!
Record recordKey = create.insertInto(table("modulerecords"),
field("id"),
field("module_id"),
field("created_date"),
field("created_by"),
field("state"),
field("tag_id"),
field("start_time",Timestamp.class),
field("kill_time", Timestamp.class),
field("feed_guid")
)
.values(null, moduleId, currentTimestamp(),
userId, state, tagId,
new Timestamp(startTime),
new Timestamp(killTime), feedGuid)
.returning(field("id"))
.fetchOne();
字段“id”是数据库中的auto_increment主键,但recordKey始终为空。
强烈建议您使用代码生成器向 DSL API 提供所有元信息。 当然,您可以不使用代码生成器,而仍然使用代码生成器原本会使用的内部 API。 您必须创建一个TableImpl
子类并覆盖/实现所有相关方法,而不是使用普通的 SQL API创建表和字段引用。
或者,您只需使用代码生成器。
从 jOOQ 3.14 开始,这可以通过将字段的数据类型指定为标识来实现,这可以使用SQLDataType.INTEGER.identity(true)
来完成。
例如,如果您有一个带有自动生成整数 id 和字符串名称的表,您可以调用:
int id = DSL.using(connection, MYSQL_5_7)
.insertInto(
table("myTable"),
field("name", String.class))
.values("John Smith")
.returning(field("id", SQLDataType.INTEGER.identity(true)))
.fetchAny(field("id", Integer.class))
所以对于你的例子,你会做
Record recordKey = create.insertInto(table("modulerecords"),
field("id"),
field("module_id"),
field("created_date"),
field("created_by"),
field("state"),
field("tag_id"),
field("start_time",Timestamp.class),
field("kill_time", Timestamp.class),
field("feed_guid")
)
.values(null, moduleId, currentTimestamp(),
userId, state, tagId,
new Timestamp(startTime),
new Timestamp(killTime), feedGuid)
.returning(field("id", SQLDataType.INTEGER.identity(true)))
.fetchOne();
有关更多背景信息,请参阅此 Github 评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.