Scala - Slick - 获取包装选项的TypedType [T]

问题描述 投票:2回答:1

通常会创建这样的自定义ID:

case class CustomID(value: Int) extends MappedTo[Int]

并使用Option [CustomID]等类型表示可空的自定义ID。但是,我希望能够将Option [_]移动到case类中,如下所示:

case class OptCustomID(optValue: Option[Int])

更具体地说,我正在寻找一个TypedType [OptCustomId],其行为类似于内置的TypedType [Option [Int]],与数据库DDL有关。

有任何想法吗?

scala slick type-safety slick-3.0
1个回答
0
投票

其实你不需要TypedType[OptCustomId]。在页面OptCustomID中描述了处理具有http://slick.lightbend.com/doc/3.3.0/userdefined.html类型字段的表的正确方法

  import slick.jdbc.PostgresProfile.api._

  case class OptCustomID(optValue: Option[Int])
  case class LiftedOptCustomID(optValue: Rep[Option[Int]])
  implicit object OptCustomIDShape extends CaseClassShape(LiftedOptCustomID, OptCustomID)

  case class Thing(id: OptCustomID, data: String)
  case class LiftedThing(id: LiftedOptCustomID, data: Rep[String])
  implicit object ThingShape extends CaseClassShape(LiftedThing.tupled, Thing.tupled)

  class ThingTable(tag: Tag) extends Table[Thing](tag, "things") {
    def id = column[Option[Int]]("id", O.PrimaryKey)
    def data = column[String]("data")
    def * = LiftedThing(LiftedOptCustomID(id), data)
  }

  val things = TableQuery[ThingTable]
  val result: DBIO[Option[Thing]] = things.filter(x => x.id === 1).result.headOption
© www.soinside.com 2019 - 2024. All rights reserved.