Where can I define methods to be called on Tables?

大兔子大兔子 提交于 2019-12-11 12:39:33

问题


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

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

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

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?


回答1:


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

foos.findByTitle("Bar")

See Scala eXchange 2013 talk our website.

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.




回答2:


I think what you want is to introduce a DAO (data access object), depending on your needs you could let the companion object of the FooTable class be the DAO which would let you call FooTable.findByTitle() from the rest of your codebase.



来源:https://stackoverflow.com/questions/24624151/where-can-i-define-methods-to-be-called-on-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!