当使用Slick CaseClass形状时,我目前面临的情况是,出于groupBy子句的效率原因,我需要在关系模型中存储三列,而在我的面向对象模型中只存在两个字段(第三个)正在计算)
case class MyEntry(quantity:Double, time:LocalDateTime){
val weight = time.getHour match {
case x if x>=7 && x<=23 => 0.1
case _ => 0.05
}
}
case class LiftedMyTuple(quantity:Rep[Double],time:Rep[LocalDateTime], weight:Rep[Double])
implicit object MyEntryShape extends CaseClassShape(???,???)
class MyTableRow(tag:Tag) extends Table[MyEntry](tag, "MY_TABLE"){
def quantity = column[Double]("QUANTITY")
def time = column[LocalDateTime]("TIME",O.PrimaryKey)
def weight = column[Double]("WEIGHT")
def * = LiftedMyTuple(quantity,time,weight)
}
如何为这样的用法编写CaseClassShape,其中case类具有应出现在关系模型中的计算属性?
答案 0 :(得分:1)
看起来构造函数是CaseClassShape(mapLifted: (LiftedTuple) ⇒ LiftedCaseClass, mapPlain: (PlainTuple) ⇒ PlainCaseClass)
我们应该能够满足这样的要求:
object myShape extends
CaseClassShape(
LiftedMyTuple.tupled,
{ (quantity, time, ignored) => MyEntry(quantity, time) }
)
如果您将案例类更改为存储权重但提供计算它的构造函数,则可以在db-&gt;代码端获取read-from-db行为,并在code-&gt; db side上计算行为。< / p>
object MyEntry {
def apply(quantity: Double, time: LocalDateTime) = {
val weight = time.getHour match {
case x if x>=7 && x<=23 => 0.1
case _ => 0.05
}
MyEntry(quantity, time, weight)
}
}
case class MyEntry(quantity: Double, time: LocalDateTime, weight: Double)
object myShape extends CaseClassShape(LiftedMyTuple.tupled, MyShape.apply.tupled)
val example = MyShape(0.0, now) // computes weight
请注意,我正在显式调用MyShape.apply
而不是MyShape
- 因为我们已经创建了一个新的apply方法,编译器将不再自动推断出MyShape
意味着{{1} (当它作为函数传递时)。