7

I need to save a Json Field as a column of my Play Framework Model. My table parser in DAO is

    class Table(tag: Tag) extends Table[Model](tag, "tablename") {
      implicit val configFormat = Json.format[Config]

      // Fields ...
      def config = column[Config]("config", O.SqlType("JSON"))
      // Fields ...

    }

Config is defined as a case class in Model in Play Model folder and has his companion object. Field of this object are Int, Double or String

    case class Config ( // fields )

    object Config {
      implicit val readConfig: Reads[Config] = new Reads[Config]
      for {
             // fields
      } yield Config(// fields)

      implicit val configFormat = Json.format[Config]

    }

Problem is i can't compile due to this error

    Error:(28, 37) could not find implicit value for parameter tt:         
        slick.ast.TypedType[models.Config]
        def config = column[Config]("config", O.SqlType("JSON"))

Is there a way to save the Config model as Json in the Table (reading it as Config)?

Paweł Jurczenko
  • 4,431
  • 2
  • 20
  • 24
emmea90
  • 357
  • 4
  • 10

1 Answers1

9

You need to tell Slick how to convert your Config instances into database columns:

implicit val configFormat = Json.format[Config]
implicit val configColumnType = MappedColumnType.base[Config, String](
  config => Json.stringify(Json.toJson(config)), 
  column => Json.parse(column).as[Config]
)
Paweł Jurczenko
  • 4,431
  • 2
  • 20
  • 24
  • It works, thank you. Do you think it's best to save the column in json or text? – emmea90 Nov 26 '16 at 18:53
  • 5
    I would store them as a JSON. There are two reasons for that: 1. Your DB engine would enforce validity of JSON values inserted into that column. 2. By storing those values as JSONs, you would be able to use additional JSON-specific functions and operators on that column. – Paweł Jurczenko Nov 27 '16 at 12:24