Slick,如何将查询映射到继承表模型? [英] Slick, how to map a query to an inheritance table model?
问题描述
Slick,如何将查询映射到继承表模型?即,
Slick, how to map a query to an inheritance table model? i.e,
我有表 A、B、CA 是父"表,B &C 是子"表我想知道的是我应该如何使用 slick 对其进行建模,这样 A 将是抽象的,而 B &C 具体类型,在 A 中查询一行将产生 B 或 C 对象
I have table A, B, C A is the "parent" table and B & C are "child" tables What I would like to know is how should I model this using slick so A will be abstract and B & C concrete types, and querying for a row in A will result in a B or C object
类似于 JPA 的 InheritanceType.TABLE_PER_CLASS
.
Something like JPA's InheritanceType.TABLE_PER_CLASS
.
推荐答案
我们需要做几件事.首先找到一种将层次结构映射到表的方法.在这种情况下,我使用一个存储类型的列.但是您也可以使用其他一些技巧.
We need to do couple of things. First find a way to map the hierarchy to an table. In this case I am using a column that stores the type. But you can use some other tricks as well.
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"))
})
}
}
现在要确定特定的子类型,您可以执行以下操作:
Now to determine specific sub type you can do following:
Query(new MyTable).foreach {
case ChildOne(a, b, c) => //childone
case ChildTwo(a, b, d) => childtwo
}
这篇关于Slick,如何将查询映射到继承表模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!