I was playing with Play and Scala. I decided to use Squeryl for Data access.
Here’s my model class models/Product.scala
package models
import org.squeryl.KeyedEntity
import org.squeryl.PrimitiveTypeMode.inTransaction
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.Schema
object AppDB extends Schema {
val productsTable = table[Product]("products")
}
case class Product (name:String,price:Long) extends KeyedEntity[Long] {
val id:Long = 0;
}
object Product {
def create (product:Product)= transaction {
AppDB.productsTable insert(product)
}
def all:Iterable[Product] = inTransaction {
val products = from (AppDB.productsTable)(productsTable =>
select(productsTable))
products.toIterable
}
}
Here’s my controller controllers/Products.scala
package controllers
import play.mvc.Controller
import play.api.mvc._
import play.api.mvc.Results._
object Products extends Controller {
def index = Action {
val products = models.Product.all
Ok(views.html.products.index(products))
}
}
Now, when I run my app localhost:8080/products I get the following error.
[RuntimeException: no session is bound to current thread, a session must be created via Session.create and bound to the thread via ‘work’ or ‘bindToCurrentThread’]
It appears that I should have wrapped the index action in Products controller around a transaction block. Here’s the updated code.
package controllers
import play.mvc.Controller
import play.api.mvc._
import play.api.mvc.Results._
object Products extends Controller {
def index = Action {
transaction {
val products = models.Product.all
Ok(views.html.products.index(products))
}
}
}
After this I was able to load products pages. I have to dig deeper to get the details. Will update when I find more information.