斯卡拉&玩! &光滑PostgreSQL自动递增 [英] Scala & Play! & Slick & PostgreSQL auto increment
问题描述
我在Scala中有以下代码:
I have the following code in 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
}
}
列出所有产品效果很好,但是,我无法使添加方法正常工作.
Listing all products works great, however, I can't make adding method working.
致电后:
val myProduct = models.Product(id = None, name = "test2", price = BigDecimal(2.99), description = "test3")
models.Products.add(myProduct)
我不断收到PostgreSQL的错误消息,说id不能为null.我完全同意这一点,但是为什么autoInc没有设置id列?这样不行吗?
I constanty get an error message from PostgreSQL saying that id cannot be null. I totally agree with that, but why the id column is not being set by autoInc? Doesn't it work that way?
我使用Play! 2.1.2,Scala 2.10.0,PostgreSQL 9.3和可播放的0.3.3.
I use Play! 2.1.2, Scala 2.10.0, PostgreSQL 9.3 and play-slick 0.3.3.
谢谢.
推荐答案
这里是一个建议,重写您的autoInc
并添加如下方法:
Here is a suggestion, rewrite your autoInc
and add methods like this:
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案.
Some databases own't allow you to insert null in the auto increment column. Maybe it's the Postgres case.
这篇关于斯卡拉&玩! &光滑PostgreSQL自动递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!