2

我发现很难找出创建可以作为 json 传递给调用客户端的类(DTO 类)实例的最佳方式。

我有以下类结构。

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 的实例并从查询结果中分配值?

4

1 回答 1

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
于 2013-09-18T12:20:06.390 回答