0

假设我想在我将与 slick 一起使用的所有案例类中都有一个 ID 列:

abstract class BaseEntity(val _id:Option[Long])
case class SomeEntity(id:Option[Long],value:String) extends BaseEntity(id)

现在让我们定义方案的抽象类和一个真正的方案:

  abstract class BaseScheme[A  <: BaseEntity](tag:Tag,name:String) extends Table[A](tag,name) {
    def id = column[Long]("ID",O.PrimaryKey,O.AutoInc)
  }
  class SomeEntityScheme(tag:Tag) extends BaseScheme[SomeEntity](tag,"SOME_NAME") {
    def value = column[String]("value",O.NotNull)
    def * = (id.?,value) <> (SomeEntity.tupled,SomeEntity.unapply)
  }

  val someEntitiesTable = TableQuery[SomeEntityScheme]

现在,因为我认为我对编写 AutoIncInsert 方法感到厌烦,所以我将创建一个通用的方法,这就是我失败的时刻:

 object BaseScheme {
     def autoIncInsert[T <: BaseScheme[_]] (t : TableQuery[T]) = t returning t.map(_.id) into {case (p,id) => p.copy(id = Some(id))}
  }

当然还有问题的输出:

[error] /home/tomaszk/Projects/4.4/mCloud/application/service-execution/execution-provisioning-model/src/main/scala/pl/mlife/mcloud/provisioning/database/schemes/ExcludingServicesScheme.scala:48: could not find implicit value for evidence parameter of type scala.slick.ast.TypedType[T#TableElementType]
[error]      def remap[T <: BaseScheme[_]] (t : TableQuery[T]) = t returning t.map(_.id) into {case (p,id) => p.copy(id = Some(id))}
[error]                                                                                                       ^
[error] one error found
4

1 回答 1

1

我的方法可能可行,我没有足够的知识说它不能,但这听起来有点可疑且过于复杂。我所做的是使用与此处相同的方法,即定义一个方法,该方法采用一个T#TableElementType(将是一个行对象)和一个TableQuery对象并执行一些通用操作:

def autoIncInsert[T <: BaseScheme[_]](row: T#TableElementType, tableReference: TableQuery[T])(implicit s: Session) = {
  (tableReference returning tableReference.map(_.id)) += row
}

然后作为类型T你应该通过SomeEntityScheme类。

在我看来,这应该以更简洁和简单的方式解决您的问题。

于 2014-05-12T22:16:32.330 回答