2016-11-26 90 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的函數和運算符。 –

相關問題