【问题标题】:Generic repository using ScalaQuery使用 ScalaQuery 的通用存储库
【发布时间】:2012-04-22 13:44:06
【问题描述】:

我正在使用出色的 ScalaQuery,我正在尝试为常见操作创建一个通用存储库,但我无法接受它。希望有人可以提供帮助。

例如,我有以下结构

abstract class Record(id : Int) 
class Product(id: Int,name:String,price : Int) extends Record(id)
class Order(id: Int,name:String,amount: Int)  extends Record(id)

以及用于产品和订单的拖车表。现在我想要通用存储库:

trait RecordRepository[T <: ExtendedTable[O]]{
     findById(id:Int) : Option[T]
     findAll() : List[T]
     save(entity:T)
     ...
}      

class ProductRepository extends RecordRepository[Product]
class ProductRepository extends RecordRepository[Order]

object ProductTable extends ExtendedTable[(Long, String, Int)]("product") {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc) 
  def name = column[String]("name", O.NotNull) 
  def price = column[Int]("price", O.NotNull) 
  def * = id ~ name ~ price 
} 
object OrderTable extends ExtendedTable[(Long, String, Int)]("order") {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc) 
  def name = column[String]("name", O.NotNull)
  def amount = column[Int]("price", O.NotNull) 
  def * = id ~ name ~ amount
}

我无法使用 for 理解来实现查询,因为描述表的元组在编译时在 trait(或抽象类)RecordRepository 中是未知的。

提前致谢!

【问题讨论】:

  • 根据提供的代码sn-p,您还没有将产品和订单模型类映射到相应的数据库表
  • 是的,我想节省空间,这里有一个简单的架构:object ProductTable extends ExtendedTable[(Long, String, Int)]("product") { def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def name = column[String]("name", O.NotNull) def price = column[Int]("price", O.NotNull) def * = id ~ name ~ price } object OrderTable extends ExtendedTable[(Long, String, Int)]("order") { def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def name = column[String]("name", O.NotNull) def amount = column[Int]("price", O.NotNull) def * = id ~ name ~ amount }

标签: scala generics repository scalaquery


【解决方案1】:

@singy 好的,很好,我以为你把那个(映射)遗漏了(你应该编辑你的答案,而不是将映射放在评论中,顺便说一句)。

尝试以下方法:
1) 将class Product 更改为case class Product
2) 将ExtendedTable[(Long, String, Int)] 替换为ExtendedTable[Product]

【讨论】:

  • @singy,认为元组是罪魁祸首;-)
猜你喜欢
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
  • 2016-02-20
  • 2021-05-18
  • 2017-04-10
相关资源
最近更新 更多