Scala + Slick how to map json to the table column

2019-09-18 03:47发布

问题:

I need to map json values to the table using slick and store whole json as a blob in the same table as well.

def createJob(jobs: JobEntity): Future[Option[Long]] =
db.run(job returning job.map((_.id)) += jobs)

My Json contains values like

id(long),name(string), type(string) 

while the table I am trying to map has columns

id(long),name(string), type(string),json_data(blob)

I have JobEntity class as

case class JobEntity(id: Option[Long] = None, name: String, type: String) {

require(!jobname.isEmpty, "jobname.empty")

}

How do I map the json to the json_data column?

回答1:

Slick supports the following LOB types: java.sql.Blob, java.sql.Clob, Array[Byte] (see the documentation)

Therefore you want to use one of these types. Your table definition could look like this:

  case class Job(id: Option[Long] = None, name: String, `type`: String, json_data: java.sql.Blob)

  class Jobs(tag: Tag) extends Table[Job](tag, "jobs") {
    def id = column[Option[Long]]("id")
    def name = column[String]("name")
    def `type` = column[String]("type")
    def json_data = column[java.sql.Blob]("json_data")
    def * = (id, name, `type`, json_data) <> (Job.tupled, Job.unapply)
  }


标签: json scala slick