3

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,
               ^
3
  • Possible duplicate of Migrating to anorm2.4 (with play 2.4): ToStatement[T] and ToStatement[Option[T]] Commented Nov 25, 2015 at 19:44
  • I added: implicit object MyClassMetaData extends ParameterMetaData[MyClass] { val sqlType = ParameterMetaData.StringParameterMetaData.sqlType val jdbcType = ParameterMetaData.StringParameterMetaData.jdbcType } which did not help me..:( Commented Nov 25, 2015 at 22:53
  • 1
    You need ToStatement & ParameterMetaData in the implicit scope. Commented Nov 25, 2015 at 23:02

1 Answer 1

0

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.