Scala + Play Framework + Slick - Json as Model Field

一曲冷凌霜 提交于 2019-12-10 20:55:40

问题


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)?


回答1:


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]
)


来源:https://stackoverflow.com/questions/40819408/scala-play-framework-slick-json-as-model-field

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