我有很多字段的案例类
case class H(
id: Int,
min: Option[String] = None,
max: Option[String] = None,
step: Option[String] = None,
...
)
如何将一些字段映射到表格?
class TH(tag: Tag) extends Table[H](tag, "H") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def min = column[Option[String]]("M")
def * = (id, min) <>(H.tupled, H.unapply)
}
当我尝试这样的时候 - def * = (id, min) <>(H.tupled, H.unapply)
,而不是映射所有字段,得到了编译异常。我可以将自定义字段映射到表格吗?
BR!
答案 0 :(得分:1)
tupled
和unapply
只是case类生成的基本函数,它定义了以下函数(以及其他内容)和case类的所有字段。
例如,对于案例类X(a: A, b: B, c: C, d: D)
,您有:
def tupled(a: a, b: b, c: c, d: d): X
def unapply(x: X): Option[(A, B, C, D)]
另一方面,使用<>
构建的投影需要参数:(f: (U => R), g: (R => Option[U]))
,其中U
是字段类型的组合。
你并没有依赖于使用&#34;自动&#34; tupled / unapply如果它们不符合您的需求,您可以提供自己的定义:
class TH(tag: Tag) extends Table[H](tag, "H") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def min = column[Option[String]]("M")
def * = (id, min) <> (
{ tuple: (Long, Option[String]) => TH(id, min) },
{ th: TH => Some((th.id, th.min)) }
)
}
答案 1 :(得分:0)
谢谢,试过了。有编译错误。无法使用=> TH
编译错误。已更改为H
。
Error:Play 2 Compiler: def * = (id, idUser) <>( {
Error:Play 2 Compiler: ^
Error:Play 2 Compiler:
}, { hq: TH => Some((hq.id, hq.idUser)) })
^
No matching Shape found.
Error:Play 2 Compiler: Slick does not know how to map the given types.
Error:Play 2 Compiler:
Possible causes: T in Table[T] does not match your * projection. Or you use an unsupported type in a Query (e.g. scala List).
Required level: slick.lifted.FlatShapeLevel
Source type: (slick.lifted.Rep[Long], slick.lifted.Rep[Long])
Error:Play 2 Compiler:
Unpacked type: (slick.lifted.Rep[Long], slick.lifted.Rep[Long])
Packed type: Any
def * = (id, idUser) <>( {
Error:Play 2 Compiler: ^
Error:Play 2 Compiler:
(compile:compileIncremental) Compilation failed
Total time: 9 s, completed Sep 3, 2015 11:58:13 AM
Error:(88, -1) Play 2 Compiler:
missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ? => ?
案例类:
case class H(
id: Option[Long] = None,
idUser: Option[Long] = None,
title: Option[String] = None,
...)
光滑的桌子:
class TH(tag: Tag) extends Table[H](tag, "H") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def idUser = column[Long]("ID_USER")
foreignKey("USER_FK", idUser, TableQuery[TUser])(_.id, onUpdate = ForeignKeyAction.Restrict, onDelete = ForeignKeyAction.Cascade)
def * = (id, idUser) <>( {
case (id: Option[Long], idUser: Option[Long]) => H(id, idUser)
}, { th: TH => Some((th.id, th.idUser)) })
}