【问题标题】:Generic AutoIncInsert in slick光滑的通用 AutoIncInsert
【发布时间】:2014-05-15 03:30:01
【问题描述】:

假设我想在我将与 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

【问题讨论】:

    标签: scala generics slick-2.0


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我有时擅长“设计”过于复杂的解决方案;)。感谢您的帮助。这正是我所需要的。
    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多