Slick 3.1.x CRUD:如何提取插入的行id?

Slick 3.1.x CRUD: how to extract the inserted row 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

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

将函数的 return 类型更改为 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)
}