[英]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.