Mapped projection with <> to a case class with companion object in Slick

后端 未结 4 792
野趣味
野趣味 2021-02-10 00:30

With Slick, I am trying to project database table entries directly to the case class they represent. Following the example in the documentation, I set up a mapped projection usi

4条回答
  •  失恋的感觉
    2021-02-10 00:42

    Another way to do it is to turn the objects apply method into a tuple and pass that to the <> as shown below.

    package models
    
    import play.api._
    import play.api.libs.json._
    import scala.slick.driver.H2Driver.simple._
    
    case class User(
      name: String,
      id: Option[Int] = None
    )
    
    object User {
      implicit val format = Json.format[User]
    }
    
    class UserTable(tag: Tag) extends Table[User](tag, "USERS") {
      def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
      def name = column[String]("NAME", O.NotNull)
    
      def * = (name, id.?) <> ((User.apply _).tupled, User.unapply)
    }
    
    object Users extends TableQuery(new UserTable(_)) {
      val findByID = this.findBy(_.id)
    }
    

提交回复
热议问题