You need to enable JavaScript to run this app. 使用slick-codegen生成表类时如何省略非必填列插入并返回自增主键?
优惠活动
大模型
产品
解决方案
定价
更多

使用slick-codegen生成表类时如何省略非必填列插入并返回自增主键?

项目依赖环境
  • 依赖版本说明:
    • play-slick 与 play-slick-evolutions 版本均为 5.0.0
    • 通过 slick-codegen(版本 3.3.3)生成数据库访问相关类
核心业务需求
  • 对应数据库表包含自增主键列、多列配置了数据库层默认值
  • 插入数据时需要实现:
    • 无需手动指定自增主键列的值
    • 无需手动指定配置了默认值的列的值
    • 插入操作执行完成后,能返回新创建行的主键值
现存问题

slick-codegen 默认生成的代码为每一张表定义独立的行数据case class,从现有代码逻辑看仅支持传入全字段完成插入。生成的代码片段如下:

case class SalesOrderRow(idSalesOrder: Int, fkCustomer: Int, createdAt: java.sql.Timestamp, createdBy: Option[String] = None)

implicit def GetResultSalesOrderRow(implicit e0: GR[Int], e1: GR[java.sql.Timestamp], e2: GR[Option[String]]): GR[SalesOrderRow] = GR{
  prs => import prs._
  SalesOrderRow.tupled((<<[Int], <<[Int], <<[java.sql.Timestamp], <<?[String]))
}

class SalesOrder(_tableTag: Tag) extends profile.api.Table[SalesOrderRow](_tableTag, Some("test"), "sales_order") {
  def * = (idSalesOrder, fkCustomer, createdAt, createdBy) <> (SalesOrderRow.tupled, SalesOrderRow.unapply)
  def ? = ((Rep.Some(idSalesOrder), Rep.Some(fkCustomer), Rep.Some(createdAt), createdBy)).shaped.<>({r=>import r._; _1.map(_=> SalesOrderRow.tupled((_1.get, _2.get, _3.get, _4)))}, (_:Any) =>  throw new Exception("Inserting into ? projection not supported."))

  val idSalesOrder: Rep[Int] = column[Int]("id_sales_order", O.AutoInc, O.PrimaryKey)
  val fkCustomer: Rep[Int] = column[Int]("fk_customer")
  val createdAt: Rep[java.sql.Timestamp] = column[java.sql.Timestamp]("created_at")
  val createdBy: Rep[Option[String]] = column[Option[String]]("created_by", O.Length(20,varying=true), O.Default(None))
}

lazy val SalesOrder = new TableQuery(tag => new SalesOrder(tag))

当前可正常运行的插入逻辑,必须显式传入所有列的值:

val insertActionsNotSoNice =
  DBIO.seq(
    salesOrders += Tables.SalesOrderRow(0, 3, new Timestamp(System.currentTimeMillis()), Some("这个不好"))
  )

尝试实现省略自增主键、默认值列的插入逻辑时,代码无法编译通过:

val insertActionsNotCompiling =
  DBIO.seq(
    salesOrders.map(so => (so.fkCustomer, so.createdBy) += (3, Some("这个好")))
  )

在公开文档、社区案例中找到的省略列插入示例,表类均直接绑定元组作为行类型,与codegen生成的自定义case class绑定的结构存在差异:

// 文档示例的表定义方式
class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES")

// codegen生成的表定义方式
class Coffees(_tableTag: Tag) extends profile.api.Table[CoffeesRow](_tableTag, Some("test"), "coffee")
待核实疑问
  • 是否必须移除slick-codegen,手动编写所有适配插入需求的表类定义?
  • 当前play-slick系列库的版本组合是否存在适配问题?
  • 是否存在未在通用文档中说明的、无需修改生成代码即可实现省略列插入的简易技巧?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 04:15:03