使用 Anorm 在 PostgreSQL json 字段中插入 Json 对象 [英] Inserting Json objects in PostgreSQL json fields with Anorm

查看:29
本文介绍了使用 Anorm 在 PostgreSQL json 字段中插入 Json 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I pass a JsObject into a json data type field in a PostgreSQL 9.3 database with Anorm without having to cast it as a string?

给定一个 PostgreSQL 9.3 表,例如:

Given a PostgreSQL 9.3 table such as:

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

使用 Play 2.2,此测试成功:

With Play 2.2, this test succeeds:

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 数据类型.

Since with Anorm we usually pass the appropriate data types instead of text (for instance, an UUID object for a column of uuid data type), it's not optimal having to convert the JsObject to a string and cast it back to the json data type in the SQL statement.

有关此问题的示例及其解决方法,请参阅使用 PostgreSQL 的Play Framework 2.1-RC1 中的原生 JSON 支持.

For an example of this issue and its workaround, please refer to Using PostgreSQL's native JSON support in Play Framework 2.1-RC1.

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

How can this be avoided with Anorm in order to pass the JsObject directly as a json data type?

推荐答案

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

For the Play 2.4 and above use the anorm.Object(value: org.postgresql.util.PGobject) class instead of value directly:

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

这篇关于使用 Anorm 在 PostgreSQL json 字段中插入 Json 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆