尝试使用anorm将\ fetch Postgres json列更新为JsValue

时间:2015-11-18 09:44:25

标签: json postgresql playframework-2.0 anorm

更新的 如果我使用普通的JsValue它可以工作,但Option [JsValue]失败了!

我正在尝试使用anorm读取和更新postgres中的json字段 以下代码应更新json:

def update(id:Long, data:Option[JsValue]){
   SQL(
      """UPDATE my_table
        |SET data = {data}
        |WHERE id = {id}
      """.stripMargin)
   .on(
       'id -> id, 
       'data -> data
   ).executeUpdate() 
}

这不是针对以下错误进行编译的:

[error]  found   : (Symbol, Option[play.api.libs.json.JsValue])
[error]  required: anorm.NamedParameter
[error]             'data -> data

基于我的一些阅读,我尝试添加隐式转换

implicit def columnToJsValue:Column[JsValue] = anorm.Column.nonNull1[JsValue] { (value, meta) =>
  val MetaDataItem(qualified, nullable, clazz) = meta
  value match {
    case json:org.postgresql.util.PGobject=> Right(Json.parse(json.getValue))
    case _=> Left(TypeDoesNotMatch(s"Cannot convert $value: ${value.asInstanceOf[AnyRef].getClass} to Json for column $qualified"))
  }
}

implicit val jsonToStatement = new ToStatement[JsValue] {
  def set(s: PreparedStatement, i: Int, json: JsValue):Unit={
    val jsonObject=new org.postgresql.util.PGobject()
    jsonObject.setType("json")
    jsonObject.setValue(Json.stringify(json))
    s.setObject(i, jsonObject)
  }
}

但它仍然无效。 我在这里错过了什么? 谢谢!

0 个答案:

没有答案