To have full control over how this data is stored you can:
- Specify the database column type when you define the column. Slick makes sensible choices here automatically, but you can use a column option of
O.SqlType
to override it with a (possibly vendor-specific) type.
- Then provide a customing mapping from your type into a value that makes sense for the database column type you want to use.
The first part is in your table definition:
class MyTable(tag: Tag) extends Table[MyClass](tag, "table_name") {
def when = column[MyDateTime]("my_date", O.SqlType("DATETIME")
// another example:
def avatar = column[Option[Array[Byte]]]("avatar", O.SqlType("BINARY(2048)"))
}
If you are using Slick to create the schema, the my_date
column will be given the type DATETIME
.
For the second part, you provide a mappling like the one in your question. It should be to/from the data type you want to use (DateTime) to a type that makes sense for the DATETIME
column. For example, the MySQL documentation indicates the format is: YYYY-MM-DD HH:MM:SS
. So what your mapping function should be able to accept and produce String
types of that format.
As an alternative...
Since Slick 3.3.0, there's built-in support for the java.time
data types. There's not a DateTime
in Java, but possibly the Java LocalDateTime
or ZonedDateTime
might suit your needs. In this case, there's no need for a mapping or an O.SqlType
.