Skip to content

Instantly share code, notes, and snippets.

@erwan
Last active December 12, 2015 01:38
Show Gist options
  • Save erwan/4692208 to your computer and use it in GitHub Desktop.
Save erwan/4692208 to your computer and use it in GitHub Desktop.
A small helper to use Slick within Play 2.1
package controllers
import play.api._
import play.api.mvc._
import play.api.Play.current
import models._
import AppDB.simple._
import Database.threadLocalSession
object Application extends Controller {
def index = Action {
AppDB.db.withSession {
Query(UserTable).foreach { u =>
Logger.info("u = " + u)
}
}
Ok(views.html.index("hola"))
}
}
package models
import play.api.Application
import scala.slick.session.Database
trait PlaySlick {
def db(implicit app: Application) = Database.forURL(
app.configuration.getString("db.default.url").getOrElse(sys.error("Missing key: db.default.url")),
app.configuration.getString("db.default.user").getOrElse(""),
driver = "scala.slick.driver.MySQLDriver"
)
}
object AppDB extends PlaySlick with scala.slick.driver.MySQLDriver {
}
package models
import AppDB.simple._
case class User(id: Option[Int], name : String)
object UserTable extends Table[User]("users") {
def id = column[Int]("id", O.PrimaryKey)
def name = column[String]("name", O.NotNull)
def * = id.? ~ name <> (User, User.unapply _)
def add(user: User)(implicit session: Session) = {
this.insert(user)
}
def countByName(name: String)(implicit session: Session) = {
(for {
user <- UserTable
if (user.name === name)
} yield(user)).list.size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment