Scala Slick通用表特征移出DAO

时间:2016-10-13 04:36:44

标签: scala playframework slick

我目前有这段代码:

class UsersRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile] {
  import driver.api._

  private val Users = TableQuery[UsersTable]

  def findByName(name: String): Future[Option[User]] =
    db.run(Users.filter(_.name === name).take(1).result.headOption)

  implicit val localDateTimeColumnType = MappedColumnType.base[LocalDateTime, Timestamp](
    d => Timestamp.from(d.toInstant(ZoneOffset.ofHours(0))),
    d => d.toLocalDateTime
  )

  trait GenericTable {
    this: Table[_] =>
    def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
    def createdAt = column[LocalDateTime]("created_at")
    def updatedAt = column[LocalDateTime]("updated_at")
  }

  private class UsersTable(tag: Tag) extends Table[User](tag, "User") with GenericTable {

    def name = column[String]("name")
    def url = column[String]("url")

    def nameIndex = index("name_index", name, unique = true)

    override def * = (id, createdAt, updatedAt, name, url) <> (User.tupled, User.unapply)
  }

}

我现在如何轻松地将GenericTable特征移出UsersRepository,以便我可以将其与其他表一起使用?如果我将其移出,则不再找到columnTableO之类的内容,因为我从驱动程序导入中删除了这些内容。

我还想将UsersTable定义本身移出DAO / repository类。在这种情况下,我遇到了同样的问题。

谢谢, 马格努斯

1 个答案:

答案 0 :(得分:0)

特征中的提供者dbConfig作为无输入参数def

trait GenericTableProvider {
  val dbConfig: DatabaseConfig[JdbcProfile]
  import dbConfig.driver.api._

  trait GenericTable {
      this: Table[_] =>

      def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
      def createdAt = column[LocalDateTime]("created_at")
      def updatedAt = column[LocalDateTime]("updated_at")
    }

}

然后使用它,如下面的代码段所示。

class UsersRepository @Inject()(protected override val dbConfigProvider: DatabaseConfigProvider) 
  extends HasDatabaseConfigProvider[JdbcProfile] 
  with GenericTableProvider {

  import driver.api._

  private val Users = TableQuery[UsersTable]

  private class UsersTable(tag: Tag) extends Table[User](tag, "User") with GenericTable {

    def name = column[String]("name")
    def url = column[String]("url")

    def nameIndex = index("name_index", name, unique = true)

    override def * = (id, createdAt, updatedAt, name, url) <> (User.tupled, User.unapply)
  }
  .....

 }

使用def dbConfigProvider

覆盖val dbConfigProvider