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

Exposed Kotlin如何实现同表字段更新为另一字段的计算结果

环境说明
  • Exposed版本:0.28.1
  • Kotlin版本:1.5.0
  • 数据库:PostgreSQL 9.4
需求背景

需要批量更新OrderDetails表所有记录的productionDate字段,赋值为当前时间戳减去同条记录的registryDate字段值,对应原生PostgreSQL SQL如下:

update order_details set production_date = current_timestamp - registry_date
Exposed ORM实现方案

常规DSL写法(推荐)

Exposed对datetime类型字段重载了算术运算符,可直接通过DSL实现,无需写原生SQL:

import org.jetbrains.exposed.sql.CurrentDateTime
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update

transaction {
    OrderDetails.update {
        it[productionDate] = CurrentDateTime() - registryDate
    }
}

如果需要添加筛选条件,可在update方法的第一个参数中传入条件表达式:

// 示例:仅更新id大于200的记录
OrderDetails.update({ OrderDetails.id greater 200 }) {
    it[productionDate] = CurrentDateTime() - registryDate
}

兼容旧版本的自定义表达式写法

如果当前版本对datetime运算的类型推断报错,可以用自定义表达式实现相同逻辑:

import org.jetbrains.exposed.sql.CustomExpression
import org.jetbrains.exposed.sql.DateTimeColumnType
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
import org.joda.time.DateTime

transaction {
    OrderDetails.update {
        it[productionDate] = CustomExpression<DateTime>(DateTimeColumnType(), "current_timestamp - fecha_registro")
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:57:03