38

我写了这段代码,它完美地工作

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 的值。

我做了谷歌,发现几篇文章

Slick 3.0.0 自动增量复合键

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

但不知何故,这些并没有干净地回答这个问题。

4

2 回答 2

67

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

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)
}
于 2015-07-16T07:39:21.617 回答
9

试试这个:

def create(name: String, price: Double): Future[Int] = db.run {
    (items returning items.map(_.id)) += Item(0, name, price)
}
于 2019-03-20T20:47:33.760 回答