加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – Slick,如何将查询映射到继承表模型?

发布时间:2020-12-16 09:28:41 所属栏目:安全 来源:网络整理
导读:光滑,如何将查询映射到继承表模型? 即, 我有表A,B,C A是“父母”表,B C是“子”表 我想知道的是我应该如何使用光滑来模拟这一点,因此A将是抽象的并且B C具体类型和查询A中的行将导致B或C对象 像JPA的InheritanceType.TABLE_PER_CLASS之类的东西. 解决方法
光滑,如何将查询映射到继承表模型?
即,

我有表A,B,C
A是“父母”表,B& C是“子”表
我想知道的是我应该如何使用光滑来模拟这一点,因此A将是抽象的并且B& C具体类型和查询A中的行将导致B或C对象

像JPA的InheritanceType.TABLE_PER_CLASS之类的东西.

解决方法

我们需要做几件事.首先找到一种将层次结构映射到表的方法.在这种情况下,我使用存储类型的列.但你也可以使用其他一些技巧.

trait Base {
  val a: Int
  val b: String
}

case class ChildOne(val a: Int,val b: String,val c: String) extends Base
case class ChildTwo(val a: Int,val d: Int) extends Base

class MyTable extends Table[Base]("SOME_TABLE") {
  def a = column[Int]("a")
  def b = column[String]("b")
  def c = column[String]("c",O.Nullable)
  def d = column[Int]("d",O.Nullable)
  def e = column[String]("model_type")

  //mapping based on model type column
  def * = a ~ b ~ c.? ~ d.? ~ e <> ({ t => t match {
    case (a,b,Some(c),_,"ChildOne") => ChildOne(a,c)
    case (a,Some(d),"ChildTwo") => ChildTwo(a,d)
  }},{
    case ChildOne(a,c) => Some((a,None,"ChildOne"))
    case ChildTwo(a,d) => Some((a,"ChildTwo"))
  })
}
}

现在要确定具体的子类型,您可以执行以下操作:

Query(new MyTable).foreach { 
     case ChildOne(a,c) => //childone
     case ChildTwo(a,d) => childtwo
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读