0
votes

I have a play application which uses slick 3 for querying Mysql DB underneath: I have defined a User case class and Users as below:

    case class User(id: Option[Int], first: String, last: String)

    class Users(tag: Tag) extends Table[User](tag, "users") {
      def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
      def first = column[String]("first")
      def last = column[String]("last")
      def * = (id.?, first, last) <> (User.tupled, User.unapply)
    }
val users = TableQuery[Users]

Now when I query the Users with last name 'Smith'. This is how it looks like

val usersTab = users.filter(usr => usr.last === 'Smith').result
val userList:List[User] = users.map(usr => User(usr.id,usr.first,usr.last)).toList 

Similarly,if I have a List[User] as userList that needs to be added to database. Then,

users.map(usr => (usr.id,usr.first,usr.last))+=((userList(0).id,userList(0).first, userList(0).last)) //Iterate over all element 

So I was expecting a much cleaner and concise way of converting List of case class to TableQuery and vice-versa. Is there a better way to do this?

Above solution works well but I have more than a dozen of table that needs to be populated. Then it starts to look ugly and repetitive.

1
concise way of converting List of case class to TableQuery by this do you mean you want a concise way to write a list of cases classes to the table?rogue-one
Yes @rogue-one , list of case classes to table and table to list of case classes.Aiden

1 Answers

1
votes

writing a list of User class instances to a table can be accomplished using the ++= method as shown below

def insert(data: List[User]) = {
  db.run(users ++= data)
}

Querying based on last name as can be done as shown below. the below method returns a Future of List of User.

def queryLastName(lastName: String): Future[List[User]] = {
  db.run(users.filter(usr => usr.last === lastName).result)
}