当从内存数据库更改为Postgres时,我遇到了Slick和Postgres的autoInc问题.拼凑了几个来源我最终得到了以下解决方案.这样可以避免在插入时向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))
}
}
Run Code Online (Sandbox Code Playgroud)
对于Slick 1.x,你采用的方式是通往你的方式.你可以这样保存一些样板:
def columns = name ~ description
def * = id.? ~: columns <> (Product, Product.unapply _) // Fields listed
def withoutId = name ~ description returning id // Fields listed again minus id
Run Code Online (Sandbox Code Playgroud)
在Slick 2.x中,autoinc列会自动被忽略,因此.insert应该正常工作.对于您确实要插入autoinc列的情况.forceInsert.
| 归档时间: |
|
| 查看次数: |
983 次 |
| 最近记录: |