我有以下耦合到模型的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提取新创建的实体。
答案 0 :(得分:1)
将您的函数的返回类型更改为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)
}