如何参数化的WHERE子句条件斯卡拉油滑查询?(How to parametrize Scala S

2019-08-06 22:05发布

假设这两个简单的查询:

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
}

我想重写它删除重复的样板来是这样的:

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)

我不知道如何去实现它有参与的理解几个隐式转换我还没解开呢。 更具体地讲:会是什么类型的??? => Boolean ??? => BooleanfindBy方法?

编辑

这些帐户和帐户类:

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 _)
}

Answer 1:

我有这样的帮手表:

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)


文章来源: How to parametrize Scala Slick queries by WHERE clause conditions?