mysqlscalaslickslick-3.0play-slick

Slick Json Column Support with MySql


I have a Json type column in MySql and I am using Scala with Slick. How can I Provide support for the Json Column via Slick.

class SampleTable(tag: Tag) extends Table[(String, ??)](tag, "test")  {

  override def * : ProvenShape[NodeReference] = (name, data)

  def name: Rep[String] = column[String]("name", O.PrimaryKey)
  def Data: Rep[??] = column[??]("data", O.PrimaryKey)

}

Any Help will be appreciated. Thanks In Advance


Solution

  • You can use a BaseColumnType to convert your JSON to a String while writing it to the database and parsing it to JSON while reading from the database:

    import play.api.libs.json.{JsValue, Json}
    
    private implicit val jsValueMappedColumnType: BaseColumnType[JsValue] =
      MappedColumnType.base[JsValue, String](Json.stringify, Json.parse)
    
    class SampleTable(tag: Tag) extends Table[(String, JsValue)](tag, "test") {
    
      def name: Rep[String] = column[String]("name", O.PrimaryKey)
    
      def data: Rep[JsValue] = column[JsValue]("data", O.PrimaryKey)
    
      def * = (name, data)
    
    }