scala – 无法使用Slick更新记录
类和表定义如下所示:
case class Group( id: Long = -1,id_parent: Long = -1,label: String = "",description: String = "") object Groups extends Table[Group]("GROUPS") { def id = column[Long]("ID",O.PrimaryKey,O.AutoInc) def id_parent = column[Long]("ID_PARENT") def label = column[String]("LABEL") def description = column[String]("DESC") def * = id ~ id_parent ~ label ~ design <> (Group,Group.unapply _) def autoInc = id_parent ~ label ~ design returning id into { case ((_,_,_),id) => id } } 要更新记录,我可以这样做: def updateGroup(id: Long) = Groups.where(_.id === id) def updateGroup(g: Group)(implicit session: Session) = updateGroup(g.id).update(g) 但我无法获得使用for表达式的更新: val findGById = for { id <- Parameters[Long] g <- Groups; if g.id === id } yield g def updateGroupX(g: Group)(implicit session: Session) = findGById(g.id).update(g) ----------------------------------------------------------------------------^ Error: value update is not a member of scala.slick.jdbc.MutatingUnitInvoker[com.exp.Group] 我显然在the documentation.中遗漏了一些东西 解决方法
更新方法由类型
UpdateInvoker 提供.如果类型的实例在范围内,则可以通过方法productQueryToUpdateInvoker和/或tableQueryToUpdateInvoker(在
BasicProfile 中找到)从Query隐式创建该类型的实例.
现在,findById方法的类型不是Query,而是BasicQueryTemplate [Long,Group].查看文档,我发现从BasicQueryTemplate(它是StatementInvoker的子类型)到UpdateInvoker,无论是隐式还是显式.考虑到这一点,这对我来说有点意义,因为我理解一个查询模板(调用者)是一个已经从一个抽象语法树(Query)“编译”到一个准备好的语句,而不是在参数化之前的早期,而一个update invoker只能从抽象语法树构建,即Query对象,因为它需要分析查询并提取其参数/列.至少这是它目前的工作方式. 考虑到这一点,一个可能的解决方案展开: def findGById(id: Long) = for { g <- Groups; if g.id === id } yield g def updateGroupX(g: Group)(implicit session: Session) = findGById(g.id).update(g) 其中findById(id:Long)的类型为Query [Groups,Group],由productQueryToUpdateInvoker转换为UpdateInvoker [Group],最终可以在其上调用update方法. 希望这有帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |