Slick 3.0 插入然后获取自动增量值
Slick 3.0 Insert and then get Auto Increment Value
我写了这段代码,效果很好
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)
}
}
此代码有效,但 return 值是插入的记录数。但是我想 return 插入完成后 AutoInc 的值。
我做了 google 并且找到了一些文章
Returning the auto incrementing value after an insert using slick
但不知何故,这些并不能清楚地回答问题。
这里是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)
}
试试这个:
def create(name: String, price: Double): Future[Int] = db.run {
(items returning items.map(_.id)) += Item(0, name, price)
}
我写了这段代码,效果很好
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)
}
}
此代码有效,但 return 值是插入的记录数。但是我想 return 插入完成后 AutoInc 的值。
我做了 google 并且找到了一些文章
Returning the auto incrementing value after an insert using slick
但不知何故,这些并不能清楚地回答问题。
这里是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)
}
试试这个:
def create(name: String, price: Double): Future[Int] = db.run {
(items returning items.map(_.id)) += Item(0, name, price)
}