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

 乀人生如梦 发布于 2023-02-04 12:30

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

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

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 个回答
  • 我相信这里最简单的方法是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)
    

    2023-02-04 12:34 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有