本文介绍了Anorm with Java 8 Date / Time API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to save timestamp field to postgresql using anorm. In scala code date/time stored as instance of java.time.Instant (someTime variable)

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

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

But anorm can't work with it now (Play 2.3.7).

什么是最好的方式让它工作?

What is the best way to make it work?

推荐答案

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

I believe most people are using JodaTime so might explain why its missing. If its not part of Anorm you can write your own converter.

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

This is untested but it would look something like below

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

这篇关于Anorm with Java 8 Date / Time API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 10:05