如何从光滑的查询创建一个类实例?

时间:2013-09-17 17:22:01

标签: scala slick

我发现很难找出最好的创建类的实例(一个DTO类),它可以作为json传递给调用客户端。

我有以下类结构。

object Suppliers extends Table[(Int, String, String, String, String, String)]("SUPPLIERS") {
  def id = column[Int]("SUP_ID", O.PrimaryKey) // This is the primary key column
  def name = column[String]("SUP_NAME")
  def street = column[String]("STREET")
  def city = column[String]("CITY")
  def state = column[String]("STATE")
  def zip = column[String]("ZIP")
  def * = id ~ name ~ street ~ city ~ state ~ zip
}

object Coffees extends Table[(Int,String, Double,Int, Int)]("COFFEES") {
  def id = column[Int]("Id",O.PrimaryKey)
  def name = column[String]("COF_NAME")
  def price = column[Double]("PRICE")
  def sales = column[Int]("SALES")
  def total = column[Int]("TOTAL")
  def * = id ~ name ~ price ~ sales ~ total
}

object CoffeeSuppliers extends Table[(Int,Int,Int)]("CoffeeSuppliers") {
    def id = column[Int]("Id",O.PrimaryKey)
    def supID = column[Int]("Sup_ID")
    def coffeeID = column[Int]("Coffee_ID")
    def supplier = foreignKey("SUP_FK", supID, Suppliers)(_.id) 
    def coffees = foreignKey("COF_FK", coffeeID,Coffees)(_.id)
    def * = id ~ supID ~ coffeeID
}

我正在使用这个简单的连接查询来检索ID为101的供应商以及他提供的所有咖啡。

            val q3 = for {
          ((cs,c),s) <- CoffeeSuppliers innerJoin 
                        Coffees on (_.coffeeID === _.id) innerJoin 
                        Suppliers on (_._1.supID === _.id) if cs.supID === 101 
        } yield (cs,c,s)

查询工作正常,我可以检索数据。 但是,我想从查询结果中构造一个DTO类。类结构就像休耕一样

  case class CoffeeDTO(
                       id:Option[Int] = Some(0),
                       name:String[String] = "",
                       price:Double= 0.0
                      )
  case class SupplierDTO (
                      id:Option[Int] = Some(0),
                      name:String = "",
                      coffees:List[CoffeeDTO] = Nil
  )

如何创建SupplierDTO的实例并从查询结果中分配值?

1 个答案:

答案 0 :(得分:2)

这样的事情怎么样:

q3.map{ case (cs,c,s) => ((s.id.?,s.name),(c.id.?,c.name,c.price)) } // remove not needed columns and make ids Options
  .list // run query
  .groupBy( _._1 ) // group by supplier
  .map{ case (s,scPairs) => SupplierDTO( s._1, // map each group to a supplier with associated coffees
                                     s._2,
                                     scPairs.map(_._2) // map group of pairs to only coffee tuples
                                            .map(CoffeeDTP.tupled) // create coffee objects
  )}
  .head // take just the one supplier out of the list