Commits

Micha Kops committed 9d46f05

Anorm queries added.

  • Participants
  • Parent commits e590c30

Comments (2)

    1. Micha Kops author

      you name it. gonna try another framework as JPA bindings work with Play-Java but not Play-Scala ... perhaps scalaquery or scala-jpa-project makes a good alternative here ...

Files changed (3)

File app/controllers/Data.scala

 import play.api.mvc.Controller
 import play.api.mvc.Result
 import models.com.hascode._
+import anorm.Pk
+import anorm.Pk
 
 object Data extends Controller {
-  val bookForm: Form[Book] = Form(mapping("title" -> text, "author" -> text)(Book.apply)(Book.unapply))
+  //val bookForm: Form[Book] = Form(mapping("id" -> number, "title" -> text, "author" -> text)(Book.apply)(Book.unapply))
 
   def test = Action {
-    Ok(views.html.myform(bookForm))
+    //Ok(views.html.myform(bookForm))
+    Ok("")
   }
 
   def post = Action { implicit request =>
-    val book = bookForm.bindFromRequest.get
+    //val book = bookForm.bindFromRequest.get
     Ok("post")
   }
 }

File app/models/com/hascode/Book.scala

 package models.com.hascode
 
-case class Book(title: String, author: String)
+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
+  }
+}

File conf/application.conf

 # Logger provided to your application:
 logger.application=DEBUG
 
+# Default database configuration using H2 database engine in an in-memory mode
+db.default.driver=org.h2.Driver
+db.default.url="jdbc:h2:mem:play"