在哪里可以定义要在表格上调用的方法? [英] Where can I define methods to be called on Tables?

查看:79
本文介绍了在哪里可以定义要在表格上调用的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我是Scala和Slick的一个完整的初学者,因此希望进行任何形式的代码审查)

(I'm a complete beginner with Scala and Slick, so code review of any kind is appreciated)

我定义了以下class和Slick Table:

I have the following class and Slick Table defined:

case class Foo(title: String, description: String, id: Int = 0)

class FooTable(tag: Tag) extends Table[Foo](tag, "FOO") {

  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def title = column[String]("TITLE", O.NotNull)
  def description = column[String]("DESCRIPTION")

  def * = (title, description, id) <> (Foo.tupled, Foo.unapply)
}

我想添加一个方法,该方法将返回与指定title匹配的FooList.像这样:

I want to add a method which will return a List of Foos which match a specified title. Something like this:

def findByTitle(title: String) = DB.withSession { implicit s: Session =>
  <FooTable TableQuery>.filter(_.title === title)
}

然后我将能够使用如下方法:

I'd then be able to use the method like this:

val foos = TableQuery[FooTable]
DB.withSession { implicit s: Session =>
  val anId = foos.findByTitle("bar")
}

如何/在何处添加可以对特定Table作用于TableQuery的方法?这甚至是安排我的申请的正确方法吗?

How/where can I add a method which can act on a TableQuery for a particular Table? Is this even the correct way to be arranging my application?

推荐答案

implicit class FooTableExtensions(q: Query[FooTable,Foo]){
  def findByTitle(t: String) = q.filter(_.title === t)
}

foos.findByTitle("Bar")

请参阅Scala eXchange 2013,请访问我们的网站.

See Scala eXchange 2013 talk our website.

对于预编译查询,使用DAO可能会很有用,您可以在其中缓存预编译查询.请参阅Scala Days 2013演讲.从那时起,语法发生了变化.查看手册Compiled.

For pre-compiled queries it may be useful to have a DAO though, where you can cache the pre-compiled query. See Scala Days 2013 talk. Syntax changed since then though. Check the manual for Compiled.

这篇关于在哪里可以定义要在表格上调用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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