如何为使用Slick插入的记录获取自动递增的值?以下代码打印1111.我原本预计它会打印1234
import scala.slick.driver.H2Driver.simple._
object TestMappedTable extends App{
case class User(id: Option[Int], first: String, last: String)
object Users extends Table[User]("users") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def first = column[String]("first")
def last = column[String]("last")
def * = id.? ~ first ~ last <> (User, User.unapply _)
}
implicit val session = Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver").createSession()
session.withTransaction{
Users.ddl.create
print(Users.insert(User(None, "Jack", "Green" )))
print(Users.insert(User(None, "Joe", "Blue" )))
print(Users.insert(User(None, "John", "Purple" )))
print(Users.insert(User(None, "Jim", "Yellow" )))
}
}
我正在使用Slick 0.11.2 for Scala 2.10.0-RC1
答案 0 :(得分:11)
您可以像这样检索生成的值。
将autoInc
方法添加到Users
对象。
def autoInc = id。? 〜第一〜最后&lt;&gt; (User,User.unapply _)返回id
改为使用Users.autoInc.insert
。
print(Users.autoInc.insert(用户(无,“杰克”,“绿色”)))
另见:
https://github.com/slick/slick/issues/10
https://github.com/slick/slick/commit/09a65a8e88a0363412e218dc5c06023b69809649
答案 1 :(得分:9)
最新版本的Slick(2.1.0)自动处理ignoring the auto-incremented ids,文档演示了如何检索id:
val userWithId =
(users returning users.map(_.id)
into ((user,id) => user.copy(id=Some(id)))
) += User(None, "Stefan", "Zeiger")
这是完整的monty,然后将检索到的值插回到要添加到表中的对象中。如果你只想亲自动手身份:
val userId =
(users returning users.map(_.id)) += User(None, "Stefan", "Zeiger")
这两段代码片段均来自官方文档。看起来这个问题需要更新给那些从未使用早期版本Slick的新人(比如我)。
答案 2 :(得分:0)
根据SLICK Inserting document,您应该定义一个方法forInsert
,如下所示:
def forInsert = first ~ last <> (
{ t =>
User(None, t._1, t._2)},
{ (u: User) =>
Some((u.first, u.last))
}) returning id
获得结果:
def save(user: User): User = {
val id = users.forInsert.insert(user)
new User(Some(id), user.first, user.last)
}
答案 3 :(得分:0)
对我来说,关注源码(Slick 3.0.2)
class Track(tag: Tag)
extends Table[(Int, String, String)](tag, "TRACK") {
// This is the primary key column:
def id: Rep[Int] = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def artist: Rep[String] = column[String]("ARTIST")
def name: Rep[String] = column[String]("NAME")
def * : ProvenShape[(Int, String, String)] =
(id, artist, name)
}