我正在使用 Slick
将案例类映射到表。在某些情况下,我需要有一个数据库表中没有的附加字段。该字段值将根据某些业务条件进行更新。
但是,我无法这样做,因为案例类和光滑表需要具有相同的字段。
在带有 Hibernate
的 java
中,使用 @Transient
注释实现了同样的效果。我该如何解决这个问题?我通过向案例类字段添加 @transient
注释来绑定(bind)。但是,光滑的映射显示了编译错误。
最佳答案
这个怎么样?
case class Container(name: String, width: Float, height: Float, isApproved: Boolean)
val c: Container = ...
val approvedContainer = c.copy(isApproved=true)
在 Slick 中
...
def * = (name, width, height, false) <> (Container.tupled, Container.unapply)
...
我还没有尝试过,您可能会遇到上述问题的插入问题,您可以解决也可以不解决。
另一种方法:
case class Container(name: String, width: Float, height: Float)(val isApproved: Boolean)
object Container{
def applyFunction = (Container.apply _).tupled
def approve(c: Container) = applyFunction(Container.unapply(c).get)(true)
def createNonApproved = (t: (String, Float, Float)) => applyFunction(t)(false)
}
在 Slick 中
...
def * = (name, width, height, false) <> (Container.createNonApproved, Container.unapply)
...
请注意,案例类的相等性仅比较第一个参数列表。
scala> Container("foo",1,2)()
res2: Container = Container(foo,1.0,2.0)
scala> Container.approve(res2)
res3: Container = Container(foo,1.0,2.0)
scala> res2 == res3
res4: Boolean = true
scala> res2.isApproved
res5: Boolean = false
scala> res3.isApproved
res6: Boolean = true
关于java - Slick 中的 transient 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28360414/