slickでauto incrementを設定する(Play Framework 2.1)
カラムidをauto-incrementにしたいとする。
ポイントは以下の通り。
1.class Userの引数idをOptionでくるむ
2.object UsersのカラムidにO.AutoIncを設定する
3.メソッドautoIncを作成する、この際returining idとすると便利
4.各メソッド(*, autoIncなど)のカラムidにautoIncであることを示す".?"を付加
case class User(id: Option[Int], email: String, name: String, password: String)
object Users extends Table[User]("user") {
lazy val database = Database.forDataSource(DB.getDataSource())
def id = column[String]("id", O.PrimaryKey, O.AutoInc)
def email = column[String]("email")
def name = column[String]("name")
def password = column[String]("password")
def autoInc = id.? ~ email ~ name ~ password <>(User.apply _, User.unapply _) returning id
def * = id.? ~ email ~ name ~ password <>(User.apply _, User.unapply _)
}
これにより、以下を実行するとauto-incrementされたidが返るようになります。
参考:
http://stackoverflow.com/questions/13114255/getting-autoincrement-values-with-slick-library-in-scala
comments powered by Disqus