Slick:返回带有自动增量ID的插入行

时间:2016-04-07 05:49:43

标签: mysql scala playframework slick

我正在尝试插入MySQL表并返回具有自动增量ID的行。我的代码如下:

private val Log = TableQuery[GCMLogTable]

def save(log: GCMLog): Try[GCMLog] = Try {
    val newId = (Log returning Log.map(_.id)) += log
    log.copy(id = newId)
}

但是我的代码编译失败,出现以下错误:

type mismatch;
    found   : slick.profile.FixedSqlAction[Long,slick.dbio.NoStream,slick.dbio.Effect.Write]
    required: Long

也试过

def save(log: GCMLog): Try[GCMLog] = Try {
    (Log returning Log.map(_.id)
      into ((log, newId) => log.copy(id = newId))
      ) += log
}

但仍然失败

type mismatch;
found   : slick.profile.FixedSqlAction[models.GCMLog,slick.dbio.NoStream,slick.dbio.Effect.Write]
required: models.GCMLog

[我在这里提到了问题How to catch slick postgres exceptions for duplicate key value violations和Slick文档http://slick.typesafe.com/doc/3.1.1/queries.html]

非常感谢有人能告诉我发生了什么以及如何解决这个问题。

谢谢!

2 个答案:

答案 0 :(得分:3)

 def save(log: GCMLog): Try[GCMLog] = Try {
    (Log returning Log.map(_.id))
       into ((log, newId) => log.copy(id = newId))
        ) += log
  }

更新:

需要执行db.run才能将Action转换为结果。

答案 1 :(得分:1)

光滑支持它:

def create(objectToCreate: MyCaseClass): MyCaseClass = {
    db.withSession {
      (self returning self) += objectToCreate
    }
  }