scala Slick 3.0 Insert 然后获取 Auto Increment Value

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31443505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:21:22  来源:igfitidea点击:

Slick 3.0 Insert and then get Auto Increment Value

scalaslickslick-3.0

提问by Knows Not Much

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

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.

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

i did google and found few articles

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

Slick 3.0.0 AutoIncrement Composite Key

Slick 3.0.0 AutoIncrement 复合键

Returning the auto incrementing value after an insert using slick

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

But somehow these do not answer the question cleanly.

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

回答by dcastro

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

回答by aleck

Try this one instead:

试试这个:

def create(name: String, price: Double): Future[Int] = db.run {
    (items returning items.map(_.id)) += Item(0, name, price)
}