Slick:如何在结果集中获取对象属性?
Slick: how to get an object attribute in a result set?
鉴于以下 Scala class 增强了 Slick:
class Users(tag: Tag) extends Table[(Int, String, String)](tag, "users") {
def id: Rep[Int] = column[Int]("sk", O.PrimaryKey)
def firstName: Rep[String] = column[String]("first_name")
def lastName: Rep[String] = column[String]("last_name")
def * : ProvenShape[(Int, String, String)] = (id, firstName, lastName)
}
我需要在查询循环中打印姓氏:
val db = Database.forConfig("dbconfig")
try {
val users: TableQuery[Users] = TableQuery[Users]
val action = users.result
val future = db.run(action)
future onComplete {
case Success(u) => u.foreach { user => println("last name : " + **user.lastName**) }
case Failure(t) => println("An error has occured: " + t.getMessage)
}
} finally db.close
但 Scala 无法识别 user.lastName
(我收到一个错误提示 "Scala doesn't recognize the symbol")。如何打印姓氏?
问题是您正在使用 Table[(Int, String, String)]
。因此,user
在您的例子中是类型 (Int, String, String)
的一个实例,因此它没有 lastName
。使用 user._3
获取元组的第三个元素(姓氏)。更好的方法可能是使用 case class 而不是元组:
case class DBUser(id: Int, firstName: String, lastName: String)
class Users(tag: Tag) extends Table[DBUser](tag, "users") {
def id: Rep[Int] = column[Int]("sk", O.PrimaryKey)
def firstName: Rep[String] = column[String]("first_name")
def lastName: Rep[String] = column[String]("last_name")
def * = (id, firstName, lastName) <> (DBUser.tupled, DBUser.unapply)
}
鉴于以下 Scala class 增强了 Slick:
class Users(tag: Tag) extends Table[(Int, String, String)](tag, "users") {
def id: Rep[Int] = column[Int]("sk", O.PrimaryKey)
def firstName: Rep[String] = column[String]("first_name")
def lastName: Rep[String] = column[String]("last_name")
def * : ProvenShape[(Int, String, String)] = (id, firstName, lastName)
}
我需要在查询循环中打印姓氏:
val db = Database.forConfig("dbconfig")
try {
val users: TableQuery[Users] = TableQuery[Users]
val action = users.result
val future = db.run(action)
future onComplete {
case Success(u) => u.foreach { user => println("last name : " + **user.lastName**) }
case Failure(t) => println("An error has occured: " + t.getMessage)
}
} finally db.close
但 Scala 无法识别 user.lastName
(我收到一个错误提示 "Scala doesn't recognize the symbol")。如何打印姓氏?
问题是您正在使用 Table[(Int, String, String)]
。因此,user
在您的例子中是类型 (Int, String, String)
的一个实例,因此它没有 lastName
。使用 user._3
获取元组的第三个元素(姓氏)。更好的方法可能是使用 case class 而不是元组:
case class DBUser(id: Int, firstName: String, lastName: String)
class Users(tag: Tag) extends Table[DBUser](tag, "users") {
def id: Rep[Int] = column[Int]("sk", O.PrimaryKey)
def firstName: Rep[String] = column[String]("first_name")
def lastName: Rep[String] = column[String]("last_name")
def * = (id, firstName, lastName) <> (DBUser.tupled, DBUser.unapply)
}