Slick 3.1.x CRUD:如何提取插入的行id? [英] Slick 3.1.x CRUD: how to extract the inserted row id?

查看:0
本文介绍了Slick 3.1.x CRUD:如何提取插入的行id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下耦合到模型的DAO实现,并在数据库中持久化一个新实体(注意能够获取序列生成的id的额外步骤),并且编译得很好(尚未实际测试):

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

现在我尝试使DAO泛型并与模型分离,并拥有(请查看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)
}

但这会导致编译器错误:

[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

首先,我不确定为什么返回类型与耦合版本不同,以及如何修复/提取具有分配的序列ID的新创建的实体。

推荐答案

将函数的返回类型更改为Future[Entity[PK]]而不是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)
}

这篇关于Slick 3.1.x CRUD:如何提取插入的行id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆