Slick 3.0 Insert 然后获取 Auto Increment Value [英] Slick 3.0 Insert and then get Auto Increment Value

查看:31
本文介绍了Slick 3.0 Insert 然后获取 Auto Increment Value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这段代码,效果很好

I have written this code which works perfectly

class Items(tag: Tag) extends Table[Item](tag, "ITEMS") {
  def id = column[Long]("ITEMS_ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("ITEMS_NAME")
  def price = column[Double]("ITEMS_PRICE")
  def * = (id, name, price) <> ((Item.apply _).tupled, Item.unapply _)
}

object Shop extends Shop{
  val items = TableQuery[Items]
  val db = Database.forConfig("h2mem1")

  def create(name: String, price: Double) : Int = {
    val action = items ++= Seq(Item(0, name, price))
    val future1 = db.run(action)
    val future2 = future1 map {result => 
      result map {x => x}
    }
    Await.result(future2, Duration.Inf).getOrElse(0)
  }
}

此代码有效,但返回值是插入的记录数.但我想在插入完成后返回 AutoInc 的值.

This code works but the return value is number of records inserted. But I want to return the value of the AutoInc after the insert has been done.

我用谷歌搜索了几篇文章

i did google and found few articles

Slick 3.0.0 AutoIncrement Composite Key

使用插入后返回自动递增值光滑

但不知何故,这些并不能清楚地回答问题.

But somehow these do not answer the question cleanly.

推荐答案

这里是 相关文档页面,根据该页面,您应该构造如下查询:

Here's the relevant documentation page, according to which, you should construct a query like this:

val insertQuery = items returning items.map(_.id) into ((item, id) => item.copy(id = id))

def create(name: String, price: Double) : Future[Item] = {
  val action = insertQuery += Item(0, name, price)   
  db.run(action)
}

这篇关于Slick 3.0 Insert 然后获取 Auto Increment Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆