【问题标题】:Slick, how to map a query to an inheritance table model?Slick,如何将查询映射到继承表模型?
【发布时间】:2013-02-15 08:12:34
【问题描述】:

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

我有桌子 A、B、C A 是“父”表,B & C 是“子”表 我想知道的是我应该如何使用 slick 进行建模,这样 A 将是抽象类型,而 B & C 具体类型,并且在 A 中查询一行将导致 B 或 C 对象

类似于 JPA 的 InheritanceType.TABLE_PER_CLASS。

【问题讨论】:

  • Slick 不是 ORM!如果您有一个围绕 ORM 类型的继承模型设计的架构,那么当您尝试在 Slick 中使用它时,您可能会遇到整个阻抗不匹配问题......
  • 我知道它不是 ORM,但是对于一个为您提供某种形式的行对象映射的框架,我想知道是否考虑到这种继承情况

标签: scala scalaquery slick


【解决方案1】:

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

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 b: String, 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, b, c)
    case (a, b, _, Some(d), "ChildTwo") => ChildTwo(a, b, d)
  }}, {
    case ChildOne(a, b, c) => Some((a, b, Some(c), None, "ChildOne"))
    case ChildTwo(a, b, d) => Some((a, b, None, Some(d), "ChildTwo"))
  })
}
} 

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

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

【讨论】:

【解决方案2】:

Slick 不直接支持这一点。不过,有些数据库可以帮助您进行继承,因此您应该能够获得接近预期效果的东西。

看看inheritance documentation in PostgreSQL

【讨论】:

    猜你喜欢
    • 2014-04-03
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    相关资源
    最近更新 更多