简体   繁体   English

如何使用 Anorm map 到 class 的一行?

[英]How can I map a Row to a class using Anorm?

I have a class User :我有一个 class User

case class User (id: Int, name: String)

And I would like to map the rows from a query using Anorm Stream API .我想 map 使用异常 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?如何将 map SqlRow转换为 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:但是使用这段代码,我得到了一个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?我之前应该有User object 吗? and I still have my case class User .我还有我的case class User

You can use Magic helper, create a object that extends magic:您可以使用魔术助手,创建一个扩展魔术的 object:

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.每个行user都是一本字典。 I don't know the Scala syntax very well.我不太了解 Scala 语法。

To make it a bit more scalable you could do this.为了使其更具可扩展性,您可以这样做。

Create a val and map the incoming data to a user.创建一个val和 map 将传入数据发送给用户。

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:现在,当您想从数据库中获取用户并将 map 获取给您的用户 class 时,您可以执行以下操作:

val selectUsers = SQL("SELECT id, name FROM users").as(parsedValueOfUser *)

I ran into this exact issue and took me awhile to finger out what was wrong.我遇到了这个确切的问题并花了我一段时间来找出问题所在。 It turned out to be the model and database names have to be the same, case-sensitive.结果是 model 并且数据库名称必须相同,区分大小写。

So for your example your database table would need to be called "User"因此,对于您的示例,您的数据库表需要被称为“用户”

You can change a database table name using: RENAME TABLE users TO User;您可以使用以下方法更改数据库表名: RENAME TABLE users TO User;

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM