Slick中的瞬态等价物

时间:2015-02-06 07:11:04

标签: java scala slick case-class transient

我使用Slick将案例类映射到表。在某些案例类中,我需要有一个在数据库表中没有的附加字段。此字段值将根据某些业务条件进行更新。 但是,我无法做到这一点,因为case类和slick表需要具有相同的字段。

在使用java的{​​{1}}中,使用Hibernate注释实现了相同的效果。我该如何解决这个问题?我将@Transient注释添加到案例类字段中。但是,光滑的映射显示编译错误。

4 个答案:

答案 0 :(得分:4)

这个怎么样?

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

请注意https://issues.scala-lang.org/browse/SI-3664

答案 1 :(得分:1)

你试过这个吗?

case class Container(name: String, width: Float, height: Float, condition: Boolean)

class Containers(tag: Tag) extends Table[Container](tag, "CONTAINERS") {
  def name = column[String]("NAME", O.PrimaryKey)
  def width = column[Float]("WIDTH")
  def height = column[Float]("HEIGHT")

  def applyBusinessCondition(): Boolean = ...

  def * = (name, width, height, applyBusinessCondition()) <> (Container.tupled, Container.unapply)
}

我认为您可以在Container类内部或外部使用函数,并在Table的*投影中调用它。您也可以在Table定义中将条件设置为False,然后再更改它。

答案 2 :(得分:1)

遇到同样的问题,用这段代码解决了:

case class Container(name: String, width: Float, height: Float, isApproved: Boolean)

class Containers(tag: Tag) extends Table[Container](tag, "CONTAINERS") {

  def name = column[String]("NAME", O.PrimaryKey)
  def width = column[Float]("WIDTH")
  def height = column[Float]("HEIGHT")

  def create = (name: String, width: Float, height: Float) =>
    Container(name, width, height, isApproved = false)

  def destroy(container: Container) =
    Some((container.name, container.width, container.height))

  def * = (name, width, height) <> (create.tupled, destroy)
}

答案 3 :(得分:0)

我没有试过@jvican解决方案。我会尝试的。但是我在不改变案例类和光滑映射表的字段的情况下以另一种方式解决了它。

我创造了一个特质

trait Approvable[TId <:AnyVal]{
  var isApproved: Boolean = false
}

然后我在我的案例类中混合了Approvable特征。检查业务条件后,我使用true / false更新isApproved字段。

相关问题