You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jooq插入操作后未更新对象生成ID问题求助

获取jOOQ插入后生成的ID值

我使用DSL上下文执行插入操作,代码如下:

val userRecord = create.newRecord(ITR_NE_USER, user)
val x = create.executeInsert(userRecord)

我期望执行插入后,userRecord会被更新为包含生成的ID(使用Kotlin语言),但插入后该ID仍为null。请问如何获取返回的生成ID值?

解决方法

  • 用executeReturning替代executeInsert,它会自动把生成的主键填充回userRecord对象:

    val userRecord = create.newRecord(ITR_NE_USER, user)
    create.executeReturning(userRecord)
    val generatedId = userRecord.id // 此时ID已被赋值
    
  • 也可以直接通过链式调用获取生成ID,无需依赖对象更新:

    val generatedId = create.insertInto(ITR_NE_USER)
        .set(create.newRecord(ITR_NE_USER, user))
        .returning(ITR_NE_USER.ID)
        .fetchOne()
        ?.value(ITR_NE_USER.ID)
    

说明

executeInsert仅返回受影响的行数,不会自动回填生成的主键。executeReturning会触发数据库返回生成的主键,并将其设置到传入的Record对象中;第二种方式则是显式指定要返回的主键字段,直接获取结果值。

内容的提问来源于stack exchange,提问作者mikeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:22:02