Anorm with Java 8 Date/Time API

房东的猫 提交于 2019-12-12 06:14:02

问题


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

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

What is the best way to make it work?


回答1:


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


来源:https://stackoverflow.com/questions/28031715/anorm-with-java-8-date-time-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!