Reputation: 11
I'm starting develop with Play 2.2.1 and Scala 2.10.2. I'm developing a CRUD application. I'm following a example from book "Play for Scala: Covers 2", but I've a problem.
In these book there is this code in model
import play.api.Play.current
import play.api.db.DB
def getAll: List[Product] = DB.withConnection { implicit connection =>
sql().map
( row =>
Product(row[Long]("id"), row[Long]("ean"), row[String]("name"), row[String]("description"))
).toList
}
But when I try run it, I recieve this error:
value map is not a member of anorm.SqlQuery
Why doesn't function .map?
Thanks you!
Upvotes: 0
Views: 738
Reputation: 9168
SqlQuery is being made private (pending PR), so it should not be used directly. In place SQL("...") or SQL"..." functions can be used, in a safer way.
Best
Upvotes: 0
Reputation: 55569
SqlQuery
doesn't have a map
function. I'm not sure how the example in the book is supposed to look, but I'm a little wary of it if it's using that clunky syntax for anorm. I think it should always be preferred to use result set parsers defined separately from the function itself--as you'll be able to reuse them elsewhere.
import anorm._
import anorm.SqlParser._
import play.api.Play.current
import play.api.db.DB
case class Product(id: Long, ean: Long, name: String, description: String)
object Product {
/** Describes how to transform a result row to a `Product`. */
val parser: RowParser[Product] = {
get[Long]("products.id") ~
get[Long]("products.ean") ~
get[String]("products.name") ~
get[String]("products.description") map {
case id ~ ean ~ name ~ description => Product(id, ean, name, description)
}
def getAll: List[Product] = {
DB.withConnection { implicit connection =>
SQL("SELECT * FROM products").as(parser *)
}
}
}
I've made the assumption that your table is named products
. It's best to use the full column names in parsers (products.id
instead of id
), as if later you need to combine parsers (using joined results), then anorm won't get confused from multiple tables using a similar column name like id
. The getAll
function now looks so much cleaner, and we can re-use the parser for other functions:
def getById(id: Long): Option[Product] = {
DB.withConnection{ implicit connection =>
SQL("SELECT * FROM products WHERE id = {id}")
.on("id" -> id)
.as(parser.singleOpt)
}
}
Upvotes: 1
Reputation: 456
In the tutorial it is mentioned that,
Before we can get any results, we have to create a query. With Anorm, you call
anorm.SQL
with your query as a String parameter:
import anorm.SQL
import anorm.SqlQuery
val sql: SqlQuery = SQL("select * from products order by name asc")
Is this missing from your code?.
Upvotes: 0