Source

play-sample-app / app / models / com / hascode / Book.scala

Full commit
package models.com.hascode

import play.api.Play.current
import anorm._
import play.api.db.DB

case class Book(
  id: Pk[Long] = NotAssigned,
  title: String,
  author: Option[String] = None) {
  def save = DB.withTransaction { implicit conn =>
    id.toOption.map { e => load(e) } match {
      case None => create
      case _ => update
    }
  }

  def create = DB.withConnection { implicit conn =>
    SQL(
      """
  	    INSERT INTO book(
  			id,
  			title,
  			author
  	    )
  	    VALUES(
  	    {id},
  	    {title},
  	    {author}
  	    )
  	    """).on(
        'id -> id.get,
        'title -> title,
        'author -> author).executeUpdate()
    this
  }

  def update = DB.withConnection { implicit conn =>
    SQL(
      """
  	    UPDATE book
        SET title={title}, author={author}
        WHERE id={id}
  	    """).on(
        'id -> id.get,
        'title -> title,
        'author -> author).executeUpdate()
    this
  }

  def load(id: Long) = DB.withConnection { implicit conn =>
    SQL(
      """
    SELECT title, author
    FROM book
    WHERE id = {id}
    """).on(
        'id -> id).single
  }
}