Scala&Play! &Slick&PostgreSQL自动增量
发布时间:2020-12-16 18:16:07 所属栏目:安全 来源:网络整理
导读:我在 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
我在
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.我完全同意这一点,但为什么id列没有被autoInc设置?它不是这样的吗? 我用Play! 2.1.2,Scala 2.10.0,PostgreSQL 9.3和play-slick 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案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |