【问题标题】:Slick transform subset of Table Columns into a Case Class将表列的子集巧妙地转换为案例类
【发布时间】:2014-10-23 02:38:20
【问题描述】:

我正在使用 Scala 2.10.2 和 Slick 2.1.0。

我有一张看起来有点像这样的桌子:

class MyTable( val tag : Tag ) extends Table[Int,Int,String]( tag, "coordinates" )
{
    def x = column[Int]( "x" )
    def y = column[Int]( "y" )
    def data = column[String]( "data" )

    def * = ( x, y, data )
}

现在,我创建了一个案例类:

case class Coordinate( val x : Int, val y : Int )

我想将我的表定义更改为如下所示:

class MyTable( val tag : Tag ) extends Table[Coordinate,String]( tag, "coordinates" )
{
    def x = column[Int]( "x" )
    def y = column[Int]( "y" )
    def data = column[String]( "data" )

    def * = ( Coordinate( x, y ), data )
}

但是,这不起作用,因为* 定义中的xColumn[Int],而不是Int。我知道您可以在表的所有列和案例类之间提供转换,有没有办法像我在这里想要的那样转换一些列?

谢谢。

【问题讨论】:

    标签: scala slick


    【解决方案1】:

    你可以试试这个:

    import play.api.db.slick.Config.driver.simple._
    import scala.slick.lifted.Tag
    
    case class Coordinate(val x: Int, val y: Int)
    
    class MyTable(val tag: Tag) extends Table[(Coordinate, String)](tag, "coordinates") {
      def x = column[Int]("x")
      def y = column[Int]("y")
      def data = column[String]("data")
    
      def * = (x, y, data).shaped <> ({
        case (x, y, data) => (Coordinate(x, y), data)
      }, { ct: Tuple2[Coordinate, String] =>
        Some(ct._1.x, ct._1.y, ct._2)
      })
    }
    
    object Coordinates {
    
      val mytable = TableQuery[MyTable]
    
      def insert(ct: (Coordinate, String))(implicit session: Session) = {
        mytable.insert(ct)
      }
    
      def search(x: Int, y: Int)(implicit session: Session): Option[(Coordinate, String)] = {
        mytable.where(_.x === x).where(_.y === y).firstOption
      }
    
    }
    

    【讨论】:

    • 想必这里的insertsearch方法是为了方便,Coordinate对象可以完全省略?
    • 修正了错字。现在对象是Coordinates,它有一些利用MyTableCoordinate 案例类的方法。不管怎样,你可以忽略object Coordinates
    猜你喜欢
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2015-01-28
    • 2022-01-11
    • 2020-03-23
    相关资源
    最近更新 更多