【问题标题】:autoInc with Postgres and Slick带有 Postgres 和 Slick 的 autoInc
【发布时间】:2013-11-12 11:55:59
【问题描述】:

从内存数据库更改为 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))
  }
}

【问题讨论】:

    标签: scala slick


    【解决方案1】:

    对于 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
    

    在 Slick 2.x 中,autoinc 列会被自动忽略,因此 .insert 应该可以正常工作。对于您确实想插入 autoinc 列的情况,请使用 .forceInsert

    【讨论】:

    • 谢谢你,这正是我所追求的。很高兴知道将来我们也可以使用 slick 2.0 进一步清理。
    猜你喜欢
    • 2014-05-26
    • 2013-10-16
    • 1970-01-01
    • 2014-05-13
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多