mmdc
mmdc

Reputation: 1746

How to reuse MappedColumnType in Table classes?

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?

Upvotes: 1

Views: 461

Answers (1)

Roman
Roman

Reputation: 5699

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

Upvotes: 3

Related Questions