I have a class User
:
case class User (id: Int, name: String)
And I would like to map the rows from a query using Anorm Stream API. I have tried with this code:
val selectUsers = SQL("SELECT id, name FROM users")
val users = selectUsers().map(
user => User(0, user.name)
).toList
But I get an error:
Error raised is : value name is not a member of play.db.anorm.SqlRow
on
user => User(0, user.↓name)
How can I map the SqlRow
to a class?
As suggested by Ricardo, I tried:
object User extends Magic[User]
val users: List[User] = SQL("SELECT * FROM users").as(User*)
But with this code I get an RuntimeException occured : ColumnNotFound(User.id)
on:
val users: List[User] = SQL("SELECT * FROM users").as(User*)
Any suggestions? Am I supposted to have the User
object in the line right before? and I still have my case class User
.
You can use Magic helper, create a object that extends magic :
object User extends Magic[User]
Then :
val users:List[User] = SQL("select * from User").as(User*)
See the doc for more information : Magic helper
I got it working with this:
val selectUsers = SQL("SELECT id, name FROM users")
val users = selectUsers().map(
user => new User(user[Int]("id"), user[String]("name"))
).toList
Every row user
is a dictionary. I don't know the Scala syntax very well.
To make it a bit more scalable you could do this.
Create a val
and map the incoming data to a user.
import {classname}
val parsedValueOfUser = {
get[Int]("id") ~
get[String]("name") map {
case id ~ name => User(id, name)
}
}
Now when you want to get a user from the database and map it to your User class you can do:
val selectUsers = SQL("SELECT id, name FROM users").as(parsedValueOfUser *)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With