scalaMap表列类型转换不应用

eivnm1vs  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(270)

我有一个类reporttemplate,它有字段过滤器。现在reporttemplaterow是表示reporttemplate的db类。我想要的是在reporttemplate中有jsonast.jvalue类型的过滤器,但是在reporttemplaterow中有字符串(当保存在db上时)。。。。我希望reporttemplate和reporttemplaterow之间的转换自动进行。
下面的代码正在工作,但显然没有任何转换…因此,每次需要在代码中使用reporttemplate时,我都必须显式地将reporttemplate转换为reporttemplateresponse。。。
我知道我应该跳过apply和unapply方法,但是我不能准确地找出…我用不同的关键字搜索了这个问题,但是找不到确切的答案。

case class ReportTemplate(id: Long, reportId: Long, name: String, group : Option[String], filter : String, created : DateTime)

class ReportTemplateRow(tag: Tag) extends Table[ReportTemplate](tag, "ReportTemplate"){
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def reportId = column[Long]("reportId")
  def name = column[String]("name")
  def group = column[Option[String]]("group")
  def filter = column[String]("filter", O.SqlType("text"))
  def created = column[DateTime]("created",O.SqlType("timestamp not null default CURRENT_TIMESTAMP"))

  def * = (id, reportId, name, group, filter, created) <> (ReportTemplate.tupled, ReportTemplate.unapply)

我期望得到的是类似于以下的东西:

case class ReportTemplate(id: Long, reportId: Long, name: String, group : Option[String], filter : JsonAST.JValue, created : DateTime)
object ReportTemplate {
  def unapply(r: ReportTemplate) : (Long, Long, String, Option[String], String, DateTime) = (r.id, r.name, r.group, JsonAST.compactRender(r.filter), r.created)
  def apply(id: Long, reportId: Long, name: String, group : Option[String], filter : String, created : DateTime) : ReportTemplate =
    ReportTemplate(id, reportId, name, group, parse(filter), created)
}

class ReportTemplateRow(tag: Tag) extends Table[ReportTemplate](tag, "ReportTemplate"){
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def reportId = column[Long]("reportId")
  def name = column[String]("name")
  def group = column[Option[String]]("group")
  def filter = column[String]("filter", O.SqlType("text"))
  def created = column[DateTime]("created",O.SqlType("timestamp not null default CURRENT_TIMESTAMP"))

  def * = (id, reportId, name, group, filter, created) <> (ReportTemplate.apply, ReportTemplate.unapply)
c86crjj0

c86crjj01#

我理解你的问题,你有一个文本数据库列( filter )你想在scala中用不同的类型来处理它。
slick为此提供了一种基于列的机制 MappedColumnType.base .
这个想法是:
在数据库row类中,您可以根据需要键入列(本例中为json)。
您还提供了从该类型(json)到数据库类型(string)的隐式转换。
详细信息在手册中,也在第5章的精髓滑头教程中。
在大纲中,对于您的情况,它可能是与此(注意:不会编译;只是一个草图):

implicit val filterTypeMapping =
    MappedColumnType.base[Json, String](
      json => json.toString, // or however you do this for the JSON you're using
      txt  => json.parse(txt).get /// or however you do this in the JSON lib you're using
    )

在这个范围内,slick将“学习”如何将json数据类型转换为对数据库友好的类型。
请注意,将文本解析为json可能会失败。这可能是运行时错误,或者您可以选择将其表示为其他类型,例如 Try[Json] 或者类似的。

相关问题