简体   繁体   English

Play Framework 2.0的Anorm上的Joda DateTime字段

[英]Joda DateTime Field on Play Framework 2.0's Anorm

I've been learning Play Framework, and the recommended way to access a database is using the build in anorm component. 我一直在学习Play Framework,访问数据库的推荐方法是使用anorm组件中的build。 Thing is, there's no good support for DateTime in anorm. 事实上,在anorm中没有对DateTime的良好支持。 It's still using java.util.Date . 它仍在使用java.util.Date

Is there any way to use Joda DateTime or java.sql.Timestamp in anorm? 有没有办法在anorm中使用Joda DateTime或java.sql.Timestamp?

If there's no way to use Joda or java.sql, can we add a module for that? 如果没有办法使用Joda或java.sql,我们可以为此添加一个模块吗?

update : Since play 2.3.7 this is now natively supported . 更新 :自从播放2.3.7以来,现在本机支持

I am using the following piece of code to work with DateTime seamlessly with Anorm. 我正在使用以下代码与Anorm无缝地使用DateTime。

import org.joda.time._
import org.joda.time.format._
import anorm._

object AnormExtension {


val dateFormatGeneration: DateTimeFormatter = DateTimeFormat.forPattern("yyyyMMddHHmmssSS");

implicit def rowToDateTime: Column[DateTime] = Column.nonNull { (value, meta) =>
    val MetaDataItem(qualified, nullable, clazz) = meta
    value match {
        case ts: java.sql.Timestamp => Right(new DateTime(ts.getTime))
        case d: java.sql.Date => Right(new DateTime(d.getTime))
        case str: java.lang.String => Right(dateFormatGeneration.parseDateTime(str))  
        case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass) )
    }
}

implicit val dateTimeToStatement = new ToStatement[DateTime] {
    def set(s: java.sql.PreparedStatement, index: Int, aValue: DateTime): Unit = {
        s.setTimestamp(index, new java.sql.Timestamp(aValue.withMillisOfSecond(0).getMillis()) )
    }
}

}

I think it should definitively be part of Anorm, just need to be polished and more tested. 我认为它应该最终成为Anorm的一部分,只需要进行抛光和更多测试。 Let me know if it has helped you. 如果有帮助,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM