2

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

Chandan
  • 11,465
  • 1
  • 6
  • 25
Akash Sethi
  • 2,284
  • 1
  • 20
  • 40

1 Answers1

9

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)

}
Chandan
  • 11,465
  • 1
  • 6
  • 25
Jack Bourne
  • 386
  • 5
  • 10
  • I have a column in Mysql of Type `JSON` – Akash Sethi Jan 22 '19 at 06:06
  • In my answer i used the scala Json classes, but you can use the java one (JSON) the same way. The important thing is to write your json to a string while writing it to a database and to parse it from a string while reading from the db. This is possible independent of your JSON library – Jack Bourne Jan 22 '19 at 07:53