Skip to content

Instantly share code, notes, and snippets.

@6temes
Created June 16, 2015 12:33
Show Gist options
  • Save 6temes/d8b11579d274e40993f4 to your computer and use it in GitHub Desktop.
Save 6temes/d8b11579d274e40993f4 to your computer and use it in GitHub Desktop.
SLICK 3.0 and Scala PlayFramework 2.4.0 -- Get results from Database.
// Model
case class Thing(id: Option[Int], name: String)
object Thing {
implicit val fmt = Json.format[Thing]
}
class Things(tag: Tag) extends Table[Thing](tag, "thing") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def * = (id.?, name) <> ((Thing.apply _).tupled, Thing.unapply)
}
object Things {
private val db = Database.forConfig("h2mem1")
private object things extends TableQuery[Things](tag ⇒ new Things(tag)) {
def all = things.result
}
private def filterQuery(id: Int): Query[Things, Thing, Seq] =
things.filter(_.id === id)
def findById(id: Int): Future[Thing] = db.run(filterQuery(id).result.headOption)
}
// Controller
class ThingController extends Controller {
def get(id: Int) = Action.async {
Things.findById(id).map(thing => Ok(Json.obj("result" -> thing)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment