scala Slick 3.0插入,然后获取自动增量值

68bkxrlz  于 8个月前  发布在  Scala
关注(0)|答案(2)|浏览(84)

我写了这个代码,它工作得很好。

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 AutoIncrement Composite Key
Returning the auto incrementing value after an insert using slick
但不知何故,这些并没有清楚地回答这个问题。

bpzcxfmw

bpzcxfmw1#

下面是相关的文档页面,根据它,你应该像这样构造一个查询:

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

kx5bkwkv2#

试试这个:

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

相关问题