1

(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?

sam-w
  • 7,478
  • 1
  • 47
  • 77

2 Answers2

2
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.

cvogt
  • 11,260
  • 30
  • 46
  • Thanks, that makes sense! Re: Scala Days 2013, did you mean the Slick vs ORM talk? – sam-w Jul 08 '14 at 23:12
  • My architecture has evolved thanks to the advice from various sources about using a DAO. I'm now trying to deal with the same problem in a different environment: http://stackoverflow.com/questions/24669616/where-to-put-my-database-access-methods-when-using-a-dao-with-slick-2-0. I'd appreciate your help if you have time! – sam-w Jul 10 '14 at 06:16
1

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.

johanandren
  • 11,249
  • 1
  • 25
  • 30
  • Thanks for the headsup on DAOs - I can see more than a few benefits to using them. – sam-w Jul 08 '14 at 23:35
  • My architecture has evolved thanks to the advice from various sources about using a DAO. I'm now trying to deal with the same problem in a different environment: http://stackoverflow.com/questions/24669616/where-to-put-my-database-access-methods-when-using-a-dao-with-slick-2-0. I'd appreciate your help if you have time! – sam-w Jul 10 '14 at 06:16