问题描述
假设我有一个表,其中包含许多小列和一个大列(例如BLOB):
Suppose I have a table with a number of small columns, and a large (say BLOB) column:
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
列以外的所有列.在其他情况下,我想将其包括在内.我更喜欢使用案例类而不是元组.
Under some circumstances, I'd like to query the table for all the columns except the large
column. In others, I'd like to include it. I prefer to use case classes rather than tuples.
Slick中是否有执行此操作的良好模式?
Is there good pattern in Slick for doing this?
我考虑过的选项:
- 具有两个映射-瘦"和胖"映射.
- 将大列拆分为单独的表,然后根据需要将其加入.
推荐答案
我认为您需要的是TableQuery
上的map
函数,以允许您仅选择字段的子集.像这样:
I think what you need here is the map
function on your TableQuery
to allow you to select only a subset of fields. So something like this:
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激活器模板,在选择特定的列"部分中(完全扩展了教程信息之后).
So I added another case class called LiteThing
that represents the subset of fields, excluding the large
column. I then use map
to create a new query that will not select that large
field and it maps to a LiteThing
. I have no compiled this, but I'm pretty sure this is the direction you want to go in. I got this from the Hello Slick Activator Template, in the section "Selecting Specific Columns" (after fully expanding the tutorial info).
您可以尝试使用类似的替代方法
You can play around with alternatives like
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)
这篇关于光滑-可选地包括/省略大列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!