【问题标题】:Trying to insert using Slick with the newly generated ID from the db尝试使用 Slick 从数据库中新生成的 ID 插入
【发布时间】:2017-03-09 18:01:30
【问题描述】:
def insert(u: User): Future[User] = {
  val insertQuery = users returning users.map(_.id) into ((user, id) => user.copy(id = id))
  val action = insertQuery += u
  db.run(action)
}

case class User(id: Int, name: String, ..)

当我使用这样的用户调用此方法时:

User(0, "john", ..)

我得到错误:

原因:org.postgresql.util.PSQLException: ERROR: duplicate key 值违反了唯一约束“users_pmkey”

它似乎试图插入 0 作为 PK。在我的 DAO 中,我将列设置为:

def id = column[Int]("id", O.PrimaryKey)

我基本上是在尝试做两件事:

  1. 插入用户
  2. 用postgresql新生成的ID返回User。

我做错了什么?

【问题讨论】:

    标签: scala playframework slick


    【解决方案1】:

    如果你的ID是postgresql生成的,可以使用O.AutoInc

    def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
    

    在您的案例类中,为您的 id 字段使用 Option:

    case class User(id: Option[Int], name: String, ..)
    

    并像这样创建您的新用户:

    User(None, "john", ..)
    

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 2011-06-06
      • 2020-04-08
      • 2013-01-10
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      相关资源
      最近更新 更多