如何在Table类中重用MappedColumnType?

时间:2015-06-15 18:45:51

标签: scala playframework slick

在此示例中演示了MappedColumnType的使用:

https://github.com/playframework/play-slick/blob/master/samples/computer-database/app/dao/ComputersDAO.scala#L21

如何在另一个表类中重用dateColumnType

1 个答案:

答案 0 :(得分:3)

例如,您可以将其移动到这样的特征:

trait DateColumnMapper extends HasDatabaseConfig[JdbcProfile] {
  protected val dbConfig: DatabaseConfig[JdbcProfile]
  import driver.api._

  implicit val dateColumnType = MappedColumnType.base[Date, Long](
    d => d.getTime,
    d => new Date(d)
  )
}

然后,您可以将此特征包含在您需要的任何DAO或db组件中:

class WhateverDAO
  extends WhateverComponent
  with HasDatabaseConfig[JdbcProfile]
  with DateColumnMapper {

  class Whatevers(tag: Tag) extends Table[Whatever](tag, "WHATEVER") {
    def anyDate = column[Option[Date]]("ANYDATE")
    ...
  }
}