2016-11-26 44 views
1

我需要将Json字段保存为我的Play Framework模型的一列。在DAO我的表解析器Scala + Play Framework + Slick - Json作为Model字段

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被定义为在播放模式文件夹中模型的情况下阶层和有他的同伴对象。此对象的字段是中等,双人或字符串

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] 

    } 

问题是我不能编译由于此错误

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

有没有办法保存配置模型为JSON在表(阅读它作为配置)?

回答

1

你需要告诉油滑如何将Config实例转换成数据库列:

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

它的工作原理,谢谢。你认为最好将json或text保存为列吗? – emmea90

+0

我会将它们存储为JSON。有两个原因: 1.您的数据库引擎会强制插入到该列中的JSON值的有效性。 2.通过将这些值存储为JSON,您可以在该列上使用其他特定于JSON的函数和运算符。 –

相关问题