在从内存数据库切换到Postgres时,我遇到了Slick和Postgres的自增问题。通过拼凑多个来源,我最终得出了以下解决方案。这避免了在插入操作中向Id列提供Null,并返回插入记录的id,但代价是需要在表的3个不同位置重复字段。有没有什么方法可以改进这个问题?尤其是对于withoutId定义,以及要求列出字段的插入本身。
case class Product(
id: Option[Long],
name: String,
description: String
)
object Products extends Table[Product]("products") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def description = column[Int]("description")
def * = id.? ~ name ~ description <> (Product, Product.unapply _) // Fields listed
def withoutId = name ~ description returning id // Fields listed again minus id
def insert(product: Product): Product = {
val id = DB withSession {
withoutId.insert(product.name, product.description) // Fields listed again
}
product.copy(id = Option(id))
}
}