【问题标题】:Anorm with Java 8 Date/Time API带有 Java 8 日期/时间 API 的异常
【发布时间】:2015-01-19 18:59:54
【问题描述】:

我尝试使用 anorm 将时间戳字段保存到 postgresql。在 scala 代码中存储为 java.time.Instant 实例的日期/时间(someTime 变量)

DB.withConnection() { implicit c => 
    SQL("INSERT INTO t_table(some_time) values ({someTime})").on('someTime -> someTime)
}

但现在 anorm 无法使用它(播放 2.3.7)。

最好的方法是什么?

【问题讨论】:

标签: scala datetime playframework playframework-2.3 anorm


【解决方案1】:

我相信大多数人都在使用 JodaTime,所以可以解释为什么它丢失了。如果它不是 Anorm 的一部分,您可以编写自己的转换器。

这是未经测试的,但它看起来像下面

import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.TimeZone

import anorm._

object InstantAnormExtension {
  val dateFormatGeneration = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss-Z")

  implicit def rowToDateTime: Column[Instant] = Column.nonNull { (value, meta) =>
    val MetaDataItem(qualified, nullable, clazz) = meta
    value match {
      case ts: java.sql.Timestamp => Right(ts.toInstant)
      case d: java.sql.Date => Right(d.toInstant)
      case str: java.lang.String => Right(Instant.from(dateFormatGeneration.parse(str)))
      case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass) )
    }
  }
  implicit val dateTimeToStatement = new ToStatement[Instant] {
    def set(s: java.sql.PreparedStatement, index: Int, aValue: Instant): Unit = {
      if(aValue == null) {
        s.setTimestamp(index, null)
      } else {
        s.setTimestamp(index, java.sql.Timestamp.from(aValue) )
      }
    }
  }
}

【讨论】:

  • 是的。使用 java 8 现在似乎越来越多的人会忘记 joda-time。战略上明智的。但也许不是。 log4j 直到使用 f.e.
猜你喜欢
  • 2014-11-08
  • 2013-07-05
  • 2016-09-07
  • 2016-05-08
  • 2015-12-26
  • 2018-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多