How to return a sequence generation for an Id

左心房为你撑大大i 提交于 2019-12-10 19:49:29

问题


In Scala Slick, if you are not using auto-incremented Id, but with sequence generation strategy for the id, how do you return that id?


回答1:


Let's say you have the following case class and Slick table:

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 _)
}

The important things to consider here is the fact that User.id is an Option, because when we create it we will set it to None and the DB will generate the number for it.

Now you need to define a new insert mapping which omits the autoincremented column. This is needed because some databases don't allow you to insert into a column which is labeled as Auto Incremental. So instead of:

INSERT INTO users VALUES (NULL, "first, "last")

Slick will generate:

INSERT INTO user(first, last) VALUES ("first", "last")

The mapping looks like this (which must be placed inside Users):

def forInsert = first ~ last <> ({ t => User(None, t._1, t._2)}, { (u: User) => Some((u.first, u.last))})

Finally getting the auto-generated id is simple. We only need to specify in the returning the id column:

val userId = Users.forInsert returning Users.id insert User(None, "First", "Last")

Or you could instead move the returning statement:

def forInsert = first ~ last <> ({ t => User(None, t._1, t._2)}, { (u: User) => Some((u.first, u.last))}) returning id

And simplify your insert calls:

val userId = Users.forInsert insert User(None, "First", "Last")

Source



来源:https://stackoverflow.com/questions/19877185/how-to-return-a-sequence-generation-for-an-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!