Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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,
               ^
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...