scala slick 2.0.2无法自动映射到自定义类

时间:2014-05-31 07:41:25

标签: scala mapping slick

我开始使用Slick,但我无法弄清楚如何在我的自定义案例类中获取查询结果。 这是我的代码:

package main.scala.model.Tree

import scala.slick.driver.H2Driver.simple._

case class SlickNode(id : Long, parentId : Long, stateString : String) 
    extends AbstractNode{}

object SlickNode {
    val nodes = TableQuery[SlickNodes]
    def findById(x : Long) : SlickNode = nodes.filter(_.id == x).first
    def findByParentId(x : Long) : Iterable[SlickNode] = nodes.filter(_.parentId == x).list

}

class SlickNodes(tag: Tag) extends Table[(Long, Long, String)](tag, "NODES") {
    def id = column[Long]("NODE_ID", O.PrimaryKey, O.AutoInc)
    def parentId = column[Long]("PARENT")
    def stateString = column[String]("STATE")
    def * = (id, parentId, stateString) <> ((SlickNode.apply _).tupled , SlickNode.unapply)
}

我期望的是从*定义中所述的从(Long,Long,String)到SlickNode的自动转换。 我错过了什么吗? 先感谢您。 亲切的问候

********* 编辑 ********* 我认为问题在我的代码中更深入。 当我尝试编译它时,我收到此错误:

[error] No matching Shape found.
[error] Slick does not know how to map the given types.
[error] Possible causes: T in Table[T] does not match your * projection. Or you use an unsupported type in a Query (e.g. scala List).
[error]   Required level: scala.slick.lifted.ShapeLevel.Flat
[error]      Source type: scala.slick.lifted.MappedProjection[main.scala.model.Tree.SlickNode,(Long, Long, String)]
[error]    Unpacked type: (Long, Long, String)
[error]      Packed type: Any
[error]   def * = (id, parentId, stateString) <> ((SlickNode.apply _).tupled , SlickNode.unapply)
[error]                                       ^

1 个答案:

答案 0 :(得分:1)

问题在于您正在扩展三元组表,而不是SlickNodeRow

class AbstractNode

case class SlickNodeRow(id : Long, parentId : Long, stateString : String) extends AbstractNode

object SlickNode {
  val nodes = TableQuery[SlickNodes]
  def findById(x : Long)(implicit s: Session): Option[SlickNodes#TableElementType] = nodes.filter(_.id === x).firstOption
  def findByParentId(x : Long) : Iterable[SlickNodeRow] = nodes.filter(_.parentId == x).list
}

class SlickNodes(tag: Tag) extends Table[SlickNodeRow](tag, "NODES") {
                                             * here   
  def id = column[Long]("NODE_ID", O.PrimaryKey, O.AutoInc)
  def parentId = column[Long]("PARENT")
  def stateString = column[String]("STATE")
  def * = (id, parentId, stateString) <> ((SlickNodeRow.apply _).tupled , SlickNodeRow.unapply)
}

投影功能并不知道如何将三元组映射到SlickNodeRow案例类。如果要返回三元组,则代码应如下所示:

class Suppliers(tag: Tag) extends Table[(Int, String, String)](tag, "SUPPLIERS") {
  def id = column[Int]("SUP_ID", O.PrimaryKey)
  def name = column[String]("SUP_NAME")
  def street = column[String]("STREET")
  def * = (id, name, street)
}
val suppliers = TableQuery[Suppliers]

As shown here,投影不会返回案例类,而是返回三元组。也许你可以用一种从三元组中返回SlickNodeRow的方式编写你的投影方法,但我不确定。