【发布时间】: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