Getting autoincrement values with Slick library in Scala

Jack picture Jack · Oct 29, 2012 · Viewed 9.9k times · Source

How do I get the auto-incremented values for records inserted with Slick? The following code prints 1111. I would have expected it to print 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" )))
  }
}

I'm using Slick 0.11.2 for Scala 2.10.0-RC1

Answer

Kazuhiro Sera picture Kazuhiro Sera · Oct 29, 2012

You can retrieve the generated value like this.

Add autoInc method to Users object.

def autoInc = id.? ~ first ~ last <> (User, User.unapply _) returning id

Use Users.autoInc.insert instead.

print(Users.autoInc.insert(User(None, "Jack", "Green" )))

See also:

https://github.com/slick/slick/issues/10

https://github.com/slick/slick/commit/09a65a8e88a0363412e218dc5c06023b69809649