Play + Anorm + Postgres - load json value into a case class

不问归期 提交于 2021-02-11 12:35:58

问题


I am using anorm to query and save elements into my postgres database. I have a json column which I want to read as class of my own.

So for example if I have the following class

case class Table(id: Long, name:String, myJsonColumn:Option[MyClass])
case class MyClass(site: Option[String], user:Option[String])

I am trying to write the following update:

DB.withConnection { implicit conn =>
    val updated = SQL(
      """UPDATE employee
        |SET name = {name}, my_json_column = {myClass}
        |WHERE id = {id}
      """.stripMargin)
      .on(
        'name -> name,
        'myClass -> myClass,
        'custom -> id
      ).executeUpdate()
  }
}

I also defined a implicit convertor from json to my object

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

And the error I get is:

type mismatch;
found   : (Symbol, Option[com.MyClass])
required: anorm.NamedParameter
        'myClass -> myClass,
               ^

回答1:


The solution is just to add the following:

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

and:

implicit object MyClassMetaData extends ParameterMetaData[MyClass] {
   val sqlType = "OTHER"
   val jdbcType = Types.OTHER
}


来源:https://stackoverflow.com/questions/33776526/try-to-update-fetch-postgres-json-column-into-jsvalue-using-anorm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!