Slick 2.0:如何将提升的查询结果转换为案例类?

时间:2014-01-12 17:58:32

标签: scala slick

为了实现ReSTfull API堆栈,我需要将从数据库中提取的数据转换为JSON格式。我认为最好的方法是从数据库中提取数据,然后使用Json.toJson()将行集转换为JSON,在定义了隐式序列化程序(写入)之后作为参数传递一个case类。

这是我的案例类和伴侣对象:

package deals.db.interf.slick2

import scala.slick.driver.MySQLDriver.simple._
import play.api.libs.json.Json

case class PartnerInfo(
    id: Int, 
    name: String, 
    site: String, 
    largeLogo: String, 
    smallLogo: String, 
    publicationSite: String
)

object PartnerInfo {

  def toCaseClass( ?? ) = { // what type are the arguments to be passed?
    PartnerInfo( fx(??) ) // how to transform the input types (slick) to Scala types?
  }

  // Notice I'm using slick 2.0.0 RC1 
  class PartnerInfoTable(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "PARTNER"){
        def id = column[Int]("id")
        def name = column[String]("name")
        def site = column[String]("site")
        def largeLogo = column[String]("large_logo")
        def smallLogo = column[String]("small_logo")
        def publicationSite = column[String]("publication_site")

        def * = (id, name, site, largeLogo, smallLogo, publicationSite) 
   }


  val partnerInfos = TableQuery[PartnerInfoTable]


  def qPartnerInfosForPuglisher(publicationSite: String) = { 
    for ( 
      pi <- partnerInfos if ( pi.publicationSite == publicationSite )
    ) yield toCaseClass( _ ) // Pass all the table columns to toCaseClass()
  }


  implicit val partnerInfoWrites = Json.writes[PartnerInfo]

}

我不能得到的是如何实现toCaseClass()方法以便将列类型从Slick 2转换为Scala类型 - 请注意toCaseClass()体中的函数fx()仅用于强调这一点。

我想知道是否有可能从Slick列类型中获取Scala类型,因为它明确地在表定义中传递,但我找不到如何获取它。

有什么想法吗?

1 个答案:

答案 0 :(得分:9)

我认为这里最简单的方法是在表架构中映射PartnerInfo

  class PartnerInfoTable(tag: Tag) extends Table[PartnerInfo](tag, "PARTNER"){
        def id = column[Int]("id")
        def name = column[String]("name")
        def site = column[String]("site")
        def largeLogo = column[String]("large_logo")
        def smallLogo = column[String]("small_logo")
        def publicationSite = column[String]("publication_site")

        def * = (id, name, site, largeLogo, smallLogo, publicationSite) <> (PartnerInfo.tupled, PartnerInfo.unapply)
   }

val partnerInfos = TableQuery[PartnerInfoTable]


  def qPartnerInfosForPuglisher(publicationSite: String) = { 
    for ( 
      pi <- partnerInfos if ( pi.publicationSite == publicationSite )
    ) yield pi
  }

否则,PartnerInfo.tupled应该可以解决问题:

 def toCaseClass(pi:(Int, String, String, String, String, String)) = PartnerInfo.tupled(pi)