好的 - 如果您可以修改您的Transaction
case class,那么有一个比HList
更好的解决方案(说实话,后者可能稍微有些麻烦)。
所以这是问题:假设您有以下属性的User
表:
- id
- name
- surname
- faculty
- finalGrade
- street
- number
- city
- postCode
上述列可能没有意义,但让我们将它们用作示例。处理上述内容最直接的方法是创建一个case class:
case class User(
id: Long,
name: String,
...
postCode: String)
这将从应用程序端的表格中映射出来。
现在你还可以做这个:
case class Address(street: String, number: String, city: String, postCode: String)
case class UniversityInfo(faculty: String, finalGrade: Double)
case class User(id: Long, name: String, surname: String, uniInfo: UniversityInfo, address: Address)
这篇文章将帮助您避免过多列(基本上是指您的case class / tuple中有太多属性的问题)。除此之外 - 我认为如果您有很多列,这样做总是(经常?)有益的 - 至少仅仅是出于可读性的考虑。
如何进行映射
class User(tag: Tag) extends Table(tag, "User") {
def id = column[Long]("id")
def name = column[String]("name")
def postCode = column[String]("postCode")
def * = (id, name, surname, uniInfoProjection, addressProjection) <>((User.apply _).tupled, User.unapply)
def uniInfoProjection = (faculty, finalGrade) <>((UniversityInfo.apply _).tupled, UniversityInfo.unapply)
def addressProjection = (street, number, city, city) <>((Address.apply _).tupled, Address.unapply)
}
使用自定义的SQL
映射也可以做到同样的效果。
implicit val getUserResult = GetResult(r =>
User(r.nextLong, r.nextString, r.nextString,
UniversityInfo(r.nextString, r.nextDouble),
Adress(r.nextString, r.nextString, r.nextString, r.nextString))
)
所以简单来说 - 尝试将您的字段分成多个嵌套的case类,这样您的问题应该就会消失(并且有改进可读性的好处)。如果您这样做,接近元组/ case类限制几乎永远不会是问题(甚至不需要使用
HList
)。
Transaction
案例类吗? - Paul Dolega