Search code examples
scalagenericsrepositoryscalaquery

Generic repository using ScalaQuery


I'm using the great ScalaQuery and I'm trying to create a generic repository for common operations, but I don't get along with it. Hopefully someone can help.

I have for example following structure

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)

and tow tables for product and order. Now I want generic repository:

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
}

I can not implement the querys using the for comprehension, because the tuple describing the table is not known at compile time in the trait (or abstract class) RecordRepository.

Thanks in advance!


Solution

  • @singy ok, good, thought you left that (the mapping) out (you should edit your answer rather putting the mapping in a comment, btw).

    Try the following:
    1) change class Product to case class Product
    2) replace ExtendedTable[(Long, String, Int)] with, ExtendedTable[Product]