2013-07-13 13 views
5

Ich habe den folgenden Code in Scala:Scala & Spielen! & Slick & PostgreSQL Autoinkrement

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

Auflistung aller Produkte funktioniert gut, jedoch kann ich das Hinzufügen Methode funktioniert nicht.

Nach dem Aufruf:

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

I Konstanty eine Fehlermeldung von PostgreSQL erhalten, dass id nicht null sein kann. Dem stimme ich vollkommen zu, aber warum wird die ID-Spalte nicht von autoInc gesetzt? Geht das nicht so?

Ich benutze Play! 2.1.2, Scala 2.10.0, PostgreSQL 9.3 und Play-Slick 0.3.3.

Vielen Dank im Voraus. Hier

+0

Was ist Ihr Schema? Wurde es von Slick oder von Hand erstellt? Wahrscheinlich muss die ID-Spalte vom Typ serial oder bigserial sein, wodurch sie tatsächlich int oder bigint schreibt, aber sie setzt den Standardwert auf nextval ('product_id_seq') und erstellt diese Sequenz automatisch. – Tim

+0

Es wird automatisch von Slick erstellt: 'create table" Produkt "(" id "SERIAL NOT NULL PRIMÄR KEY," Name "VARCHAR (254) NOT NULL," Preis "DECIMAL (21,2) NOT NULL," Beschreibung "VARCHAR (254) NOT NULL); '. Ich denke, es ist bereits SERIAL, aber der Code funktioniert nicht :( – oskario

Antwort

5

ist ein Vorschlag, schreiben Sie Ihre autoInc und fügen Sie Methoden wie folgt aus:

def autoInc = name ~ price ~ description returning id 

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

Einige Datenbanken own't Sie erlauben einfügen null in der Autoinkrement-Spalte. Vielleicht ist es der Postgres-Fall.

+1

Das ist richtig :) (und die Spiel-Slick Computer-Datenbank Beispiel falsch). – cvogt

+0

Perfekt! Vielen Dank. – oskario

+0

Sollte das Beispiel nicht 'add (p: Product) ...' oder '..autoInc.insert (product.name) ...' lauten? – jbnunn