首先,如果我想将带时区的日期时间映射到 Slick,我应该使用哪个类 OffsetDateTime
或 ZonedDateTime
?至于Joda,我们只能使用DateTime
。
如何为 Slick 表映射编写一些隐式代码以在 java8 ZonedDateTime
和 Sql Timestamp
之间进行转换?
使用 joda DateTime
来包含时区信息似乎非常简单。然而,一旦切换到 Java8,我不太确定我应该使用 ZonedDateTime
还是 OffsetDateTime
,如 http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html建议使用 OffsetDateTime。
对于我当前的代码,我只使用 Java8 LocalDateTime
并编写以下隐式代码以在 slick 之间进行映射。
implicit val JavaLocalDateTimeMapper = MappedColumnType.base[LocalDateTime, Timestamp](
l => Timestamp.valueOf(l),
t => t.toLocalDateTime
)
不太确定我是否可以使用 ZonedDateTime
或 OffsetDateTime
编写类似的代码?
最佳答案
简答
从 Slick 3.1 开始,简短的回答是使用 OffsetDateTime ,但您需要将其映射到 String
列,而不是 Timestamp
才能与任何数据库一起使用。
也就是说,您需要一个 MappedColumnType.base[OffsetDateTime, String]
。您可以使用 toString
和 OffsetDateTime.parse
进行字符串转换:
scala> import java.time._
import java.time._
scala> val paris = ZoneId.of("Europe/Paris")
paris: java.time.ZoneId = Europe/Paris
scala> OffsetDateTime.now(paris)
res0: java.time.OffsetDateTime = 2016-01-05T20:38:46.473+01:00
scala> OffsetDateTime.parse(res0.toString)
res2: java.time.OffsetDateTime = 2016-01-05T20:38:46.473+01:00
更长的答案
OffsetDateTime之间的区别和 ZonedDateTime包含在 What's the difference between java 8 ZonedDateTime and OffsetDateTime? 的答案中,这里不再赘述。
但是,您需要阅读它来决定简短答案是否符合您的情况。
如果您使用 Postgres,there's support for java.time通过 slick-pg项目。我自己没有机会使用它,但显然值得研究一下您正在使用的数据库。参见例如 the test suite对于“date2”附加组件。
更好的答案(或者, future 的答案!)
好消息是,有一个活跃的拉取请求要在 Slick 中添加对 java.time 数据类型的支持。可以监控进度on the ticket ,目前计划用于 Slick 3.2。
关于java - Scala Slick 3.0 java8 OffsetDateTime 和 Timestamp 之间的隐式映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34608650/