如何通过 WHERE 子句条件参数化 Scala Slick 查询? [英] How to parametrize Scala Slick queries by WHERE clause conditions?

查看:49
本文介绍了如何通过 WHERE 子句条件参数化 Scala Slick 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这两个简单的查询:

Assume these two simple queries:

def findById(id: Long): Option[Account] = database.withSession { implicit s: Session =>
  val query = for (a <- Accounts if a.id === id) yield a.*
  query.list.headOption
}

def findByUID(uid: String): Option[Account] = database.withSession { implicit s: Session =>
  val query = for (a <- Accounts if a.uid === uid) yield a.*
  query.list.headOption
}

我想重写它以删除重复的样板文件:

I would like to rewrite it to remove the boilerplate duplication to something like this:

def findBy(criteria: ??? => Boolean): Option[Account] = database.withSession {
  implicit s: Session =>
    val query = for (a <- Accounts if criteria(a)) yield a.*
    query.list.headOption
}

def findById(id: Long) = findBy(_.id === id)

def findByUID(uid: Long) = findBy(_.uid === uid)

我不知道如何实现它,因为在理解中涉及到几个隐式转换我还没有解开.更具体地说: 的类型是什么???=>findBy 方法中的布尔值?

I don't know how to achieve it for there are several implicit conversions involved in the for comprehension I haven't untangled yet. More specifically: what would be the type of ??? => Boolean in the findBy method?

编辑

这些是 Account 和 Accounts 类:

These are Account and Accounts classes:

case class Account(id: Option[Long], uid: String, nick: String)

object Accounts extends Table[Account]("account") {
  def id = column[Option[Long]]("id")
  def uid = column[String]("uid")
  def nick = column[String]("nick")
  def * = id.? ~ uid ~ nick <> (Account, Account.unapply _)
}

推荐答案

我有这个助手表:

abstract class MyTable[T](_schemaName: Option[String], _tableName: String) extends Table[T](_schemaName, _tableName) {
  import scala.slick.lifted._
  def equalBy[B: BaseTypeMapper]
    (proj:this.type => Column[B]):B => Query[this.type,T] = { (str:B) => 
     Query[this.type,T,this.type](this) where { x => proj(x) === str} }

}

现在你可以:

 val q=someTable.equalBy(_.someColumn) 
 q(someValue)

这篇关于如何通过 WHERE 子句条件参数化 Scala Slick 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆