使用 Play Slick 在 PostgreSQL 中保留 UUID - java.sql.BatchUpdateException

Persist UUID in PostgreSQL using Play Slick - java.sql.BatchUpdateException

我一直在玩 Play,在尝试将一些示例数据保存到 PostrgeSQL 中时遇到了问题。

我知道我可以将 UUID 转换为字符串并以这种方式保存,但我无法让它与 UUID 一起使用。

我得到的错误:

Error injecting constructor, java.sql.BatchUpdateException: Batch entry 0 insert into "COMPANIES" ("ID","NAME") values (?,'Amazon') was aborted: ERROR: column "ID" is of type uuid but expression is of type bytea

我的依赖项:

libraryDependencies += "org.postgresql" % "postgresql" % "42.1.4"
libraryDependencies += "com.typesafe.play" %% "play-slick" % "3.0.1"

公司案例class:

case class Company(id: UUID = UUID.randomUUID, name: String)

圆滑table定义:

val companies: TableQuery[Companies] = TableQuery[Companies]

class Companies(tag: Tag) extends Table[Company](tag, "COMPANIES") {
  override def * : ProvenShape[Company] = (id, name) <> (Company.tupled, Company.unapply)

  def id: Rep[UUID] = column[UUID]("ID", O.PrimaryKey, O.SqlType("UUID"))
  def name: Rep[String] = column[String]("NAME")
}

在日志中我注意到 UUID 确实被转换为字节:

[debug] s.j.J.statement - Preparing statement: insert into "COMPANIES" ("ID","NAME")  values (?,?)
[debug] s.j.J.parameter - /-------------+-----------\
[debug] s.j.J.parameter - | 1           | 2         |
[debug] s.j.J.parameter - | Bytes       | String    |
[debug] s.j.J.parameter - |-------------+-----------|
[debug] s.j.J.parameter - | [B@17c2de51 | Amazon    |
[debug] s.j.J.parameter - | [B@6a4e93d5 | Google    |
[debug] s.j.J.parameter - | [B@69f81ed7 | Microsoft |
[debug] s.j.J.parameter - \-------------+-----------/

非常感谢您的帮助或提示。

您必须为您的数据库系统导入特定的配置文件。你的情况:

import slick.jdbc.PostgresProfile.api._

尽管我建议注入配置提供程序,然后导入 api。这样,如果您配置另一个数据库管理系统,您的代码将工作。

class DAO @Inject()(@NamedDatabase("DB_NAME_FROM_CONFIG") protected val dbConfigProvider: DatabaseConfigProvider)
                      (implicit ec: ExecutionContext) {
  import profile.api._

  ...
}