如何使用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转换为字符串并将其转换回json数据类型并不是最佳选择. sql语句.
有关此问题及其解决方法的示例,请参阅Using PostgreSQL’s native JSON support in Play Framework 2.1-RC1.
为了将JsObject作为json数据类型直接传递,如何使用Anorm避免这种情况?
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。