簡體   English   中英

Scala和Play! &Slick&PostgreSQL自動遞增

[英]Scala & Play! & Slick & PostgreSQL auto increment

我在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
  }
}

列出所有產品效果很好,但是,我無法使添加方法正常工作。

致電后:

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

我不斷收到PostgreSQL的錯誤消息,說id不能為null。 我完全同意,但是為什么autoInc沒有設置id列? 這樣不行嗎?

我使用播放! 2.1.2,Scala 2.10.0,PostgreSQL 9.3和順暢播放0.3.3。

提前致謝。

這是一個建議,重寫您的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)
}

某些數據庫不允許您在自動增量列中插入null。 也許是Postgres案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM