数据库
首页 > 数据库> > 使用Slick / Scala将日期和时间存储到MySQL中

使用Slick / Scala将日期和时间存储到MySQL中

作者:互联网

我有一个看似简单的问题,并希望有一个简单的解决方案.但我还没有找到它.

我在MySQL中的属性是DATE和TIMESTAMP类型.
这些是我的光滑课程:

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

出于某种原因,我不能让这个工作.主要问题似乎是如何将java.util.Date存储到MySQL中的DATE和TIMESTAMP类型中.

有人可以建议如何做到这一点?我是Scala / Slick世界的新手.

解决方法:

您希望将java.util.Date存储到MySQL中的DATE和TIMESTAMP类型中,因此您需要定义转换:

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

}

标签:scala,mysql,date,slick
来源: https://codeday.me/bug/20190727/1558044.html