Scala&Play!&Slick&PostgreSQL自动增量

osk*_*rio 5 postgresql scala playframework slick playframework-2.1

我在Scala中有以下代码:

case class Product(id: Option[Long] = None, name: String, price: BigDecimal, description: String)

object Products extends Table[Product]("product") {
  def id = column[Long]("id", O.AutoInc, O.PrimaryKey)
  def name = column[String]("name", O.NotNull)
  def price = column[BigDecimal]("price", O.NotNull)
  def description = column[String]("description", O.NotNull)

  def * = id.? ~ name ~ price ~ description <>(Product.apply _, Product.unapply _)

  def autoInc = * returning id

  def add(product: Product)(implicit s:Session): Long = {
    Products.autoInc.insert(product)
  }

  def all(implicit s:Session): List[Product] = {
    Query(Products).list
  }
}
Run Code Online (Sandbox Code Playgroud)

列出所有产品效果很好,但是,我无法使添加方法有效.

致电后:

val myProduct = models.Product(id = None, name = "test2", price = BigDecimal(2.99), description = "test3")
models.Products.add(myProduct)
Run Code Online (Sandbox Code Playgroud)

我常常从PostgreSQL收到一条错误消息,说id不能为null.我完全同意这一点,但为什么id列没有被autoInc设置?它不是这样的吗?

我用Play!2.1.2,Scala 2.10.0,PostgreSQL 9.3和play-slick 0.3.3.

提前致谢.

ped*_*rla 5

这是一个建议,重写你的autoInc并添加如下方法:

def autoInc = name ~ price ~ description returning id

def add(product: Product)(implicit s:Session): Long = {
    Products.autoInc.insert(p.name, p.price, p.description)
}
Run Code Online (Sandbox Code Playgroud)

某些数据库不允许您在自动增量列中插入null.也许这是Postgres案.