我有一个像这样的伴侣对象:
object Addresses extends Table[Address]("address"){
//some mapping columns
....
//a method I want to made generic
def findAll(limit: Option[Int], offset: Option[Int]): Seq[Address] = DBTest.db.withSession { implicit db: Session =>
(limit, offset) match {
case (Some(l), Some(o)) => Addresses.map { a => a }.drop(o).take(l).list
case (None, None) => Addresses.map { a => a }.drop(ConfigurationsLoader.DefaultOffset).take(ConfigurationsLoader.DefaultLimit).list
case (Some(l), None) => Addresses.map { a => a }.take(l).list
case (None, Some(o)) => Addresses.map { a => a }.drop(o).list
}
}
案例类Address
的。
因为我有很多这样的对象(每个都定义一个表)我想在一个特性中移动findAll
方法使它成为通用的,我试着这样做:
trait DbGenericOperations[T, U <: Table[T]]{
val entities: U
/**
* Based on REST conventions, for listing it's good to use limit and offset, like: /entities?limit=25&offset=50.
*/
def findAll(limit: Option[Int], offset: Option[Int]): Seq[T] = DBTest.db.withSession { implicit db: Session =>
(limit, offset) match {
case (Some(l), Some(o)) => entities.map { a => a }.drop(o).take(l).list
case (None, None) => entities.map { a => a }.drop(ConfigurationsLoader.DefaultOffset).take(ConfigurationsLoader.DefaultLimit).list
case (Some(l), None) => entities.map { a => a }.take(l).list
case (None, Some(o)) => entities.map { a => a }.drop(o).list
}
}
}
正如您所注意到的,entities
基本上是我的伴侣对象。
现在的问题是我不能像这样重写我的对象定义:
object Addresses extends Table[Address]("address") with DbGenericOperations[Address, Addresses]{
因为它说Addresses
不是类型......
我对scala很新,我想知道:有什么方法可以解决这个问题吗?
更新:我这样做了:
trait DbGenericOperations[T]{
/**
* Based on REST conventions, for listing it's good to use limit and offset, like: /entities?limit=25&offset=50.
*/
def findAll(limit: Option[Int], offset: Option[Int], entities: Table[T]): Seq[T] = DBTest.db.withSession { implicit db: Session =>
(limit, offset) match {
case (Some(l), Some(o)) => entities.map { a => a }.drop(o).take(l).list
case (None, None) => entities.map { a => a }.drop(ConfigurationsLoader.DefaultOffset).take(ConfigurationsLoader.DefaultLimit).list
case (Some(l), None) => entities.map { a => a }.take(l).list
case (None, Some(o)) => entities.map { a => a }.drop(o).list
}
}
}
并声明这样的伴侣对象:
object Addresses extends Table[Address]("address") with DbGenericOperations[Address]
但我不喜欢使用这种方法:
val results = Addresses.findAll(limit, offset, Addresses)
如果有更好的解决方案,请告诉我......
答案 0 :(得分:1)
为什么不创建一个类/特性RichTable [T](...)扩展Table [T](...)哪个会添加这个方法?