Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I map a Row to a class using Anorm?

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.

like image 358
Jonas Avatar asked Jun 03 '11 14:06

Jonas


3 Answers

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

like image 168
Ricardo Avatar answered Nov 08 '22 23:11

Ricardo


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.

like image 37
Jonas Avatar answered Nov 08 '22 23:11

Jonas


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 *)
like image 2
malmling Avatar answered Nov 09 '22 01:11

malmling