1

假设我有一个包含许多小列和一个大(比如 BLOB)列的表:

  case class Thing(id: Int, small1: String, small2: String, small3: String, large: String)

  class ThingMapping(tag: Tag) extends Table[Thing](tag, "things") {

    def id = column[Int]("id", O.PrimaryKey, O.NotNull, O.AutoInc)
    def small1 = column[String]("small1")
    def small2 = column[String]("small2")
    def small3 = column[String]("small3")
    def large = column[String]("large")

    def * = (id, small1, small2, small3, large) <> (Thing.tupled, Thing.unapply)

  }

在某些情况下,我想查询表中除列之外的所有large列。在其他情况下,我想包括它。我更喜欢使用案例类而不是元组。

Slick 中是否有很好的模式来执行此操作?

我考虑过的选项:

  1. 有两个映射——“瘦”和“胖”映射。
  2. 将大列拆分为单独的表,然后在需要时将其加入。
4

1 回答 1

-1

我认为您在这里需要的是允许您仅选择字段子集的map功能。TableQuery所以是这样的:

case class Thing(id: Int, small1: String, small2: String, small3: String, large: String)
case class LiteThing(id: Int, small1: String, small2: String, small3: String)
class ThingMapping(tag: Tag) extends Table[Thing](tag, "things") {
  def id = column[Int]("id", O.PrimaryKey, O.NotNull, O.AutoInc)
  def small1 = column[String]("small1")
  def small2 = column[String]("small2")
  def small3 = column[String]("small3")
  def large = column[String]("large")
  def * = (id, small1, small2, small3, large) <> (Thing.tupled, Thing.unapply)
}
val things = TableQuery[ThingMapping]

val liteThingQuery = things.map(t => LiteThing(t.id, t.small1, t.small2, t.small3))

所以我添加了另一个称为LiteThing字段子集的案例类,不包括large列。然后,我使用map创建一个不会选择该large字段的新查询,并将其映射到LiteThing. 我没有编译这个,但我很确定这是你想要的方向。我从Hello Slick Activator Template中得到这个,在“选择特定列”部分(在完全扩展教程信息之后)。

你可以玩一些替代品,比如

def small = (id, small1, small2, small3)
def * = (small, large)

或者

def small = (id, small1, small2, small3)
def * = small ~ large <> (Thing.tupled, Thing.unapply)

并使用

things.map(_.small)
于 2014-09-01T12:43:02.190 回答