ps0604
ps0604

Reputation: 1071

Slick: how to get an object attribute in a result set?

Given the following Scala class enhanced with 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)
}

I need to print the last names in a query loop:

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

But Scala doesn't recognize user.lastName (I get an error saying that "Scala doesn't recognize the symbol"). How to print the last names ?

Upvotes: 0

Views: 692

Answers (1)

danielnixon
danielnixon

Reputation: 4268

The problem is you're using Table[(Int, String, String)]. user in your case is therefore an instance of type (Int, String, String), so it doesn't have a lastName. Use user._3 to get at the tuple's third element (the last name). Even better might be to use a case class instead of a tuple:

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)
}

Upvotes: 1

Related Questions