如何在ScalaQuery中撰写查询以创建可重用的特征?
我将单个查询中的不同查询组件组合起来有些麻烦.我的目标是创建一组特征(例如SoftDeletable,HasName,SortedByName,WithTimestamps),我可以简单地混合到Table对象来添加该行为.
理想的样子是: abstract class BaseModel[Tuple <: Product,CaseClass](tableName: String) extends Table[Tuple](tableName) { def id = column[Int]("id",O.AutoInc,O.PrimaryKey) def mapped: MappedProjection[CaseClass,TupleClass] def allQuery = this.map(_.mapped) final def all = database.withSession { implicit session: Session => allQuery.list() } ... } trait SoftDeletable[Tuple <: Product,CaseClass] extends BaseModel[Tuple,CaseClass] { def isActive = column[String]("is_active") def * = super.* ~ isActive def allQuery = /* here,I'd like to compose super.allQuery with a filter that returns rows where isActive is true */ } trait HasName[Tuple <: Product] extends Table[Tuple] { def name = column[String]("name") def * = super.* ~ name } trait SortedByName[Tuple <: Product] extends HasName[Tuple { override def allQuery = super.allQuery /* compose somehow with (_ <- Query orderBy name */ } 我可以用ScalaQuery做这些事情吗?主要的问题是: >如何在SoftDeletable.allQuery中清理组合过滤器,并使用BaseModel.allQuery在SortedByName.allQuery中排序? case class Foo class Foos[(Int,Int,Boolean,String),Foo] extends Table[(Int,String)] with SoftDeletable[(Int,Foo] with SortedByName[(Int,Foo] with HasName[(Int,String)] { } 我可以避免所有这些重复吗?根据jesnor在IRC上的建议,我能够避免这样的一些: abstract class SoftDeletableBaseModel[TupleClass <: Product,CaseClass](tableName: String) extends BaseModel[TupleClass,CaseClass](tableName) with SoftDeletable[TupleClass,CaseClass] 换句话说,通过将特定的特征组合在一起,我不需要重复整个元组声明;当然,不足之处在于,不可能简单地混合各种特征 – 我需要创建大量特定的子类以避免这种重复.还有另一种方式吗? 更新:所以我意识到我不需要使用单独的CaseClass和TupleClass类型参数.由于案例类实现了Product *,您只需将case类名称传递给Table即可解决3中的问题: trait SoftDeletable[CaseClass] extends BaseModel[CaseClass] { ... } class Models extends BaseModel[Model]("models") with SoftDeletable[Model] { ... } 解决方法
如果你的问题只是添加排序,这不是仅仅是一个flatMap的问题吗?
def sortBy[T,U,C](q: Query[T,U],col: NamedColumn[C]) = q.flatMap(_ => Query orderBy col) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |