How to convert query result to case class?

I am using Slick 2.0, and I have the following case class User:

case class User(id: Option[Long], email: String, password: String)

class Users(tag: Tag) extends Table[User](tag, "user") {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def email = column[String]("email")
  def password = column[String]("password")

  def * = (id.?, email, password) <> ((User.apply _).tupled, User.unapply _)
}

and I have the following function retrieving a user through its database id:

def findOneById(id: Long) = DB.withSession { implicit session =>
  val result = (for {
                  u <- users if u.id === id
                } yield (u.id, u.email, u.password)).first
  User(Option(result._1), result._2, result._3)
}

Is there an easier way to convert Seq's answer back resultto case class User?

+4
source share
3 answers

Ok, I found my answer. I got this partly from @benji and partly from this post: Converting scala.slick.lifted.Query to a case class .

Instead of using it for understanding, the following returns the [User] parameter, which is exactly what I need:

def findOneById(id: Long):Option[User] = DB.withSession { implicit session =>
  users.filter(_.id === id).firstOption
}
+3
source

sql-. :

def findOneById(id: Long) = DB.withSession { implicit session =>
    val query = for {
        u <- users if u.id === id
        t <- token if t.user_id = u.id && token.isActive === `A`
        } yield u    
    query.firstOption
}
+1

To convert the result to a list of the user case class, you can simply do

result.map(User.tupled)

However, I will only work if your data model is consistent. For example: your user class has id as optional if it is the primary key in the database, which is incorrect.

0
source

Source: https://habr.com/ru/post/1568696/


All Articles