2016-11-29 11 views
1

我有以下耦合到模型的DAO實現,並堅持一個新的實體在我的數據庫中(注意額外的步驟能夠獲取連續生成的ID),並編譯好(尚未實際測試):Slick 3.1.x CRUD:如何提取插入的行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 

我不確定首先爲什麼返回類型與耦合版本不同,以及如何修復它/使用分配的序列號提取新創建的實體。

回答

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