与浮油的通用表

时间:2016-09-14 15:14:40

标签: scala slick

我试图创建一个通用表抽象类,我可以用它来表示集合并减少样板。

这是我的第一次尝试:

abstract class StringCollectionTable[A](tag: Tag,
                                      name1: String, name2: String,
                                      table: TableQuery[A], idMapper: A => Rep[Long])
extends Table[(Long, String)](tag, name1+"_"+name2) {

def id = column[Long]("ID_"+name1)
def item = column[String](name2)

def pk = primaryKey("pk_"+name1+"_"+name2, (id, item))

def idFK = foreignKey(name1 + "_FK", id, table)(idMapper, onUpdate=ForeignKeyAction.Restrict, onDelete=ForeignKeyAction.Cascade)

override def * : ProvenShape[(Long, String)] = (id, item)
}

它可以像以下一样使用:

case class Foo(...)
class FooTable(tag: Tag) extends Table[Foo](tag, "FOO") {...}
val foos = TableQuery[FooTable]
val mapToId = (t: TableQuery[FooTable]) => t.id


class FooBarTable(tag: Tag)
extends StringCollectionTable(tag, "FOO", "BAR", foos, mapToId)

因此,我可以存储一个与一个foo相关的条形值集合。

在IntellJ IDEA中,这段代码似乎没问题。但是当我运行应用程序时,我收到错误:

inferred type arguments [slick.lifted.Rep[Long],Nothing,A,Nothing] do not conform to method foreignKey's type parameter bounds [P,PU,TT <: slick.lifted.AbstractTable[_],U]

排队:

    def idFK = foreignKey(name1 + "_FK", id, table)(idMapper, onUpdate=ForeignKeyAction.Restrict, onDelete=ForeignKeyAction.Cascade) 

我一直在做一些搜索,但我找不到问题。这是我的第一个Slick项目,我有点迷失。

有人可以告诉我这样做的正确方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

类型参数A应该是Table隐含A <: Table[_]

的子类型

声明你的StringCollectionTable就像这样

abstract class StringCollectionTable[A <: Table[_]](tag: Tag, ...) extends ... {
  ...
  override def * = (id, item)
}