【发布时间】:2014-06-14 05:57:33
【问题描述】:
我一直在寻找如何为公共 CRUD 和其他类型的操作实现通用特征,我查看了 this 和 this 并且指定的方法运行良好。
我想要的是一个通用的插入方法,我的类目前看起来像这样(非通用实现):
object CampaignModel {
val campaigns = TableQuery[Campaign]
def insert(campaign: CampaignRow)(implicit s: Session) = {
campaigns.insert(campaign)
}
}
到目前为止,我在第一个链接之后尝试过的是(通用实现):
trait PostgresGeneric[T <: Table[A], A] {
val tableReference = TableQuery[T]
def insertGeneric(row: ? What type goes here ?)(implicit s: Session) = tableReference.insert(row)
}
当我检查 insert 方法时,看起来正确的类型应该是 T#TableElementType 但我的知识非常基础,我无法理解类型,我尝试了 T 和 A 和编译器说类类型不符合 trait one 的。
其他信息,表格是用光滑的表格生成工具生成的
case class CampaignRow(id: Long, name: Option[String])
/** Table description of table campaign. Objects of this class serve as prototypes for rows in queries. */
class Campaign(tag: Tag) extends Table[CampaignRow](tag, "campaign") {
def * = (id, name) <>(CampaignRow.tupled, CampaignRow.unapply)
/** Maps whole row to an option. Useful for outer joins. */
def ? = (id.?, name).shaped.<>({
r => import r._; _1.map(_ => CampaignRow.tupled((_1.get, _2)))
}, (_: Any) => throw new Exception("Inserting into ? projection not supported."))
/** Database column id AutoInc, PrimaryKey */
val id: Column[Long] = column[Long]("id", O.AutoInc, O.PrimaryKey)
/** Database column name */
val name: Column[Option[String]] = column[Option[String]]("name")
}
【问题讨论】:
标签: postgresql scala generics slick slick-2.0