Skip to content

Instantly share code, notes, and snippets.

@mguillermin
Created March 14, 2012 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mguillermin/2035421 to your computer and use it in GitHub Desktop.
Save mguillermin/2035421 to your computer and use it in GitHub Desktop.
Play 2.0 Anorm Sample
case class User(email: String, name: String, password: String)
object User {
// -- Parsers
/**
* Parse a User from a ResultSet
*/
val simple = {
get[String]("user.email") ~
get[String]("user.name") ~
get[String]("user.password") map {
case email~name~password => User(email, name, password)
}
}
// -- Queries
/**
* Retrieve a User from email.
*/
def findByEmail(email: String): Option[User] = {
DB.withConnection { implicit connection =>
SQL("select * from user where email = {email}").on(
'email -> email
).as(User.simple.singleOpt)
}
}
/**
* Retrieve all users.
*/
def findAll: Seq[User] = {
DB.withConnection { implicit connection =>
SQL("select * from user").as(User.simple *)
}
}
/**
* Create a User.
*/
def create(user: User): User = {
DB.withConnection { implicit connection =>
SQL(
"""
insert into user values (
{email}, {name}, {password}
)
"""
).on(
'email -> user.email,
'name -> user.name,
'password -> user.password
).executeUpdate()
user
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment