假設這兩個簡單的查詢:如何通過WHERE子句條件參數化Scala查詢?
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)
我不知道如何去實現它有在理解中涉及的幾個隱式轉換我還沒有解開。更具體地說:findBy
方法中??? => Boolean
的類型是什麼?
編輯
這些帳戶和帳戶類:
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 _)
}
P租賃請參閱http://stackoverflow.com/questions/14501159/higher-order-functions-with-scala-slick-for-dry-goodness/16892497#16892497 – Sameer