【问题标题】:Inserting Json objects in PostgreSQL json fields with Anorm使用 Anorm 在 PostgreSQL json 字段中插入 Json 对象
【发布时间】:2013-11-05 03:11:12
【问题描述】:

如何使用 Anorm 将 JsObject 传递到 PostgreSQL 9.3 数据库中的 json 数据类型字段,而不必将其转换为字符串?

给定一个 PostgreSQL 9.3 表,例如:

create table profiles
(
  id serial primary key,
  profile json null
);

使用 Play 2.2,此测试成功:

package helpers

import anorm._
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.db.DB
import play.api.libs.json._
import play.api.test._

@RunWith(classOf[JUnitRunner])
class AnormTest extends Specification {
  "AnormTest" should {
    "insert a JSON object" in new WithApplication {
      val profile = Json.obj("language" -> "en")
      val sql = SQL("insert into profiles (profile) values (CAST({profile} AS json))")
        .on("profile" -> profile.toString)
      DB.withConnection { implicit c => sql.execute() }
    }
  }
}

但是随着这些行的改变:

      val sql = SQL("insert into profiles (profile) values ({profile})")
        .on("profile" -> profile)

它会产生这个错误:

org.postgresql.util.PSQLException: 
Can't infer the SQL type to use for an instance of play.api.libs.json.JsObject. 
Use setObject() with an explicit Types value to specify the type to use.

由于使用 Anorm,我们通常传递适当的数据类型而不是文本(例如,uuid 数据类型的列的 UUID 对象),将 JsObject 转换为字符串并不是最佳选择将其转换回 SQL 语句中的 json 数据类型。

有关此问题的示例及其解决方法,请参阅Using PostgreSQL's native JSON support in Play Framework 2.1-RC1。

为了将 JsObject 直接作为 json 数据类型传递,如何使用 Anorm 避免这种情况?

【问题讨论】:

    标签: json scala types playframework anorm


    【解决方案1】:

    对于 Play 2.4 及以上版本,请直接使用 anorm.Object(value: org.postgresql.util.PGobject) 类而不是 value:

    val pgObject = new org.postgresql.util.PGobject();
    pgObject.setType("json");
    pgObject.setValue(profile);
    val sql = SQL("insert into profiles (profile) values ({profile})")
        .on("profile" -> anorm.Object(pgObject))
    

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 2023-04-08
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多