Slick 3.1.x CRUD: how to extract the inserted row id?

纵饮孤独 提交于 2019-12-11 06:18:08

问题


I have the following coupled-to-model DAO implementation and to persist a new entity in the database I do (note the extra steps to be able to fetch the serially generated id) and this compiles fine (not actually tested yet):

// this is generated by the Slick codegen
case class UserRow(id: Long, ...
class User(_tableTag: Tag) extends Table[UserRow](_tableTag, "user")
lazy val User = new TableQuery(tag => new User(tag))

// function to persist a new user
def create(user: UserRow): Future[UserRow] = {
  val insertQuery = User returning User.map(_.id) into ((row, id) => row.copy(id = id))
  val action = insertQuery += user
  db.run(action)
}

Now I try to make the DAO generic and decoupled from the model and have (check the full source code in GenericDao.scala):

def create(entity: E): Future[E] = {
  val insertQuery = tableQuery returning tableQuery.map(_.id) into ((row, id) => row.copy(id = id))
  val action = insertQuery += entity
  db.run(action)
}

but this leads to the compiler error:

[error] /home/bravegag/code/play-authenticate-usage-scala/app/dao/GenericDao.scala:81: type mismatch;
[error]  found   : GenericDao.this.driver.DriverAction[insertQuery.SingleInsertResult,slick.dbio.NoStream,slick.dbio.Effect.Write]
[error]     (which expands to)  slick.profile.FixedSqlAction[dao.Entity[PK],slick.dbio.NoStream,slick.dbio.Effect.Write]
[error]  required: slick.dbio.DBIOAction[E,slick.dbio.NoStream,Nothing]
[error]       db.run(action)
[error]              ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

and I am not sure first why the return type is different from the coupled version and how to fix it/extract the newly created entity with the assigned serial id.


回答1:


Change the return type of your function to Future[Entity[PK]] instead of Future[E]

def create(entity: E): Future[Entity[PK]] = {
  val insertQuery = tableQuery returning tableQuery.map(_.id) into ((row, id) => row.copy(id = id))
  val action = insertQuery += entity
  db.run(action)
}


来源:https://stackoverflow.com/questions/40861900/slick-3-1-x-crud-how-to-extract-the-inserted-row-id

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