2013-07-13 38 views
5

我在斯卡拉以下代碼:Scala&Play! &油滑PostgreSQL及自動遞增

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) 

我constanty得到PostgreSQL的話說,ID不能爲空的錯誤消息。我完全同意這一點,但爲什麼id列沒有被autoInc設置?它不是那樣工作嗎?

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

在此先感謝。

+0

你的模式是什麼?是由光滑還是手工創建的?有可能的,id列需要是serial或bigserial類型的,它使得它的類型爲int或bigint,並且將默認值設置爲nextval('product_id_seq'),並自動創建該序列。 – Tim

+0

它由Slick自動創建:'create table「product」(「id」SERIAL NOT NULL PRIMARY KEY,「name」VARCHAR(254)NOT NULL,「price」DECIMAL(21,2)NOT NULL,「description」VARCHAR (254)NOT NULL);'。我認爲它已經是SERIAL,但代碼不起作用:( – oskario

回答

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) 
} 

有些數據庫own't允許您在自動遞增列插入空。也許這是Postgres案例。

+1

這是正確的:)(以及玩遊戲的電腦數據庫示例錯誤)。 – cvogt

+0

完美!謝謝。 – oskario

+0

這個例子不應該是'add(p:Product)...'或'..autoInc.insert(product.name)...'嗎? – jbnunn