我写的这段代码完美无缺
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
但不知怎的,这些都没有干净地回答这个问题。
答案 0 :(得分:56)
这是relevant documentation page,据此,你应该构建一个这样的查询:
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)
}
答案 1 :(得分:0)
尝试以下方法:
StatefulWidget