微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Apply UnApply上的映射表列类型转换

如何解决Apply UnApply上的映射表列类型转换

我有一个包含字段 filter 的类 ReportTemplate。现在 ReportTemplateRow 是代表 ReportTemplate 的 db 类。我想要的是在 ReportTemplate 中有 JsonAST.JValue 类型的过滤器,但在 ReportTemplateRow 中有 String (当保存在 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,filter : JsonAST.JValue,created : DateTime)
object ReportTemplate {
  def unapply(r: ReportTemplate) : (Long,Long,String,Option[String],DateTime) = (r.id,r.name,r.group,JsonAST.compactRender(r.filter),r.created)
  def apply(id: Long,created : DateTime) : ReportTemplate =
    ReportTemplate(id,parse(filter),created)
}

class ReportTemplateRow(tag: Tag) extends Table[ReportTemplate](tag,created) <> (ReportTemplate.apply,ReportTemplate.unapply)

解决方法

据我了解您的问题,您有一个文本数据库列 (filter),您希望在 Scala 中使用不同的类型。

Slick 为此提供了一种基于列的机制,如 MappedColumnType.base

想法是:

  • 在您的数据库行类中,您可以根据需要键入列(在本例中为 JSON)。
  • 您还提供了从该类型 (JSON) 到数据库类型 (String) 的隐式转换。

详细信息在 the manual 和 Essential Slick 教程 chapter 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] 或类似类型。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。