Storing date and time in MySQL using Slick / Scala
I have what seems like a simple problem and wish there was a simple solution. But I haven't found it yet.
My attributes in MySQL are of DATE and TIMESTAMP types. These are my cool classes:
case class Event (
id: Long, name: String, category: String, date: Date, venue: String, startTime: Date, endTime: Date, description: String, admission: String, addInfo: Option[String])
class Events(tag: Tag) extends Table[Event](tag, "EVENT") {
implicit val dateColumnType = MappedColumnType.base[Date, Long](d => d.getTime, d => new Date(d))
def id = column[Long]("ID", O.PrimaryKey)
def name = column[String]("NAME")
def category = column[String]("CATEGORY")
def date = column[Date]("DATE")
def venue = column[String]("VENUE")
def startTime = column[Timestamp]("START_TIME")
def endTime = column[Timestamp]("END_TIME")
def description = column[String]("DESCRIPTION")
def admission = column[String]("ADMISSION")
def addInfo = column[String]("ADD_INFO")
def * = (id, name, category, date, venue, startTime, endTime, description, admission, addInfo.?) <> (Event.tupled, Event.unapply _)
}
For some reason I cannot get this to work. The main problem is how to store java.util.Date in DATE and TIMESTAMP types in MySQL.
Can anyone advise on the best way to do this? I am new to the Scala / Slick world.
+3
source to share
2 answers
You want to store java.util.Date in both DATE and TIMESTAMP types in MySQL, so you need to define the conversion:
1) java.util.Date => java.sql.Date
2) java.util.Date => java.sql.Timestamp
class Events(tag: Tag) extends Table[Event](tag, "EVENT") {
def id = column[Long]("ID", O.PrimaryKey)
def name = column[String]("NAME")
def category = column[String]("CATEGORY")
def date = column[Date]("DATE")(DateMapper.utilDate2SqlDate)
def venue = column[String]("VENUE")
def startTime = column[Date]("START_TIME") (DateMapper.utilDate2SqlTimestampMapper)
def endTime = column[Date]("END_TIME")(DateMapper.utilDate2SqlTimestampMapper)
def description = column[String]("DESCRIPTION")
def admission = column[String]("ADMISSION")
def addInfo = column[Option[String]]("ADD_INFO")
def * = (id, name, category, date, venue, startTime, endTime, description, admission, addInfo) <> (Event.tupled, Event.unapply)
}
object DateMapper {
val utilDate2SqlTimestampMapper = MappedColumnType.base[java.util.Date, java.sql.Timestamp](
{ utilDate => new java.sql.Timestamp(utilDate.getTime()) },
{ sqlTimestamp => new java.util.Date(sqlTimestamp.getTime()) })
val utilDate2SqlDate = MappedColumnType.base[java.util.Date, java.sql.Date](
{ utilDate => new java.sql.Date(utilDate.getTime()) },
{ sqlDate => new java.util.Date(sqlDate.getTime()) })
}
+6
source to share
Have you checked out slick-joda-wrapper ? You can also check out another Scala friendly wrapper around Joda: https://github.com/nscala-time/nscala-time
0
source to share