How to reuse MappedColumnType in Table classes?

471 Views Asked by At

The use of MappedColumnType is demonstrated in this example:

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

How can I reuse dateColumnType in another table class?

1

There are 1 best solutions below

5
On BEST ANSWER

You could, for example, move it to a trait like this:

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)
  )
}

Then you can include this trait in whatever DAO or db component you need it:

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

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