【问题标题】:How to parametrize Scala Slick queries by WHERE clause conditions?如何通过 WHERE 子句条件参数化 Scala Slick 查询?
【发布时间】:2012-12-29 08:50:41
【问题描述】:

假设这两个简单的查询:

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)

我不知道如何实现它,因为我还没有解开 for 理解中涉及的几个隐式转换。更具体地说:findBy 方法中 ??? =&gt; Boolean 的类型是什么?

编辑

这些是 Account 和 Accounts 类:

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

【问题讨论】:

标签: scala scalaquery slick


【解决方案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)

【讨论】:

  • +1,不错的解决方案,但是,这与 createFinderBy 有何不同?使用 Foo.createFinderBy(_.whatever) 在 Slick 中内置了相同的功能
  • 不完全是。 createFinder 不同,因为它创建了一个 QueryTemplate 并且您可以在其中添加其他限制。我发明这个正是为了克服 createFinder 的这个限制。
  • 哦,我把单行变成多行后忘记去掉分号了。
  • 以上,我的意思是QueryTemplate不能加额外的限制
  • 当我从 ScalaQuery 切换到 Slick 时会尝试,可能会派上用场...谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 2020-05-31
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
相关资源
最近更新 更多