Scala Slick:Cusom映射器将DateTime转换为datetime

时间:2019-03-19 20:43:12

标签: scala slick

我正在尝试将DATETIME类型的DateTime对象存储到数据库中,到目前为止,我还没有看到这样的示例,而是看到了从DateTime到Timestamp或DATE在数据库中进行的一些操作。

有人在那里遇到同样的问题吗?

我的代码(目前无法正常工作)如下:

import slick.jdbc.MySQLProfile.api._
import com.github.nscala_time.time.Imports.DateTime

object CustomMappers {
   implicit def dateTimeMapper = MappedColumnType.base[DateTime, DateTime](
        tmap = { dateTimeObject => new DateTime(dateTimeObject.getMillis)},
        tcomap = { dateTimeDb => new DateTime(dateTimeDb) }
  )
}

2 个答案:

答案 0 :(得分:1)

要完全控制此数据的存储方式,您可以:

  1. 在定义列时指定数据库列的类型。 Slick会在此处自动做出明智的选择,但是您可以使用O.SqlType的列选项来使用(可能是特定于供应商的)类型覆盖它。
  2. 然后提供从您的类型到一个值的自定义映射,该值对您要使用的数据库列类型有意义。

第一部分在表定义中:

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

如果使用Slick创建架构,则my_date列的类型为DATETIME

对于第二部分,您提供了一个与问题中的映射类似的映射。它应该与您要使用的数据类型(DateTime)之间或从DATETIME列有意义的类型之间来。例如,MySQL文档指出格式为:YYYY-MM-DD HH:MM:SS。因此,您的映射功能应该能够接受并产生String种类型的格式。

作为替代...

从Slick 3.3.0开始,有built-in support for the java.time数据类型。 Java中没有DateTime,但是Java LocalDateTimeZonedDateTime可能适合您的需求。在这种情况下,不需要映射或O.SqlType

答案 1 :(得分:1)

使用光滑的3.3.0,我发现了另一个解决方法。 (IT也应适用于其他版本)

def cusDateTimeCol = column[LocalDateTime]("cusDateTimeCol", O.SqlType("datetime"))(localDateTimeMapper)

,范围如下。 (使用特征并将其导入表定义中)

  val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
  implicit def LocalDateTimeToStr(d: LocalDateTime): String = {
    d.format(formatter)
  }

  implicit def strToLocalDateTime(s: String): LocalDateTime = {
    LocalDateTime.parse(s, formatter)
  }

  implicit val localDateTimeMapper = MappedColumnType.base[LocalDateTime, String](
    LocalDateTimeToStr(_),
    strToLocalDateTime(_)
  )

使用此设置,代码将以YYYY-mm-dd HH:mm:ss格式而不是通常的ISO格式读取/写入日期时间。