Play Framework 2.0的Anorm上的Joda DateTime字段 [英] Joda DateTime Field on Play Framework 2.0's Anorm

查看:66
本文介绍了Play Framework 2.0的Anorm上的Joda DateTime字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习Play框架,建议的访问数据库的方法是使用内置的anorm组件.事实是,在主动脉中没有对DateTime的良好支持.它仍在使用java.util.Date.

I've been learning Play Framework, and the recommended way to access a database is using the build in anorm component. Thing is, there's no good support for DateTime in anorm. It's still using java.util.Date.

有什么方法可以在主动脉中使用Joda DateTime或java.sql.Timestamp?

Is there any way to use Joda DateTime or java.sql.Timestamp in anorm?

如果无法使用Joda或java.sql,我们可以为此添加模块吗?

If there's no way to use Joda or java.sql, can we add a module for that?

推荐答案

更新:自播放2.3.7以来,现在为

update: Since play 2.3.7 this is now natively supported.

我正在使用以下代码与Anorm无缝地使用DateTime.

I am using the following piece of code to work with DateTime seamlessly with Anorm.

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

}

我认为它应该绝对是Anorm的一部分,只需要进行抛光和更多测试即可. 让我知道它是否对您有帮助.

I think it should definitively be part of Anorm, just need to be polished and more tested. Let me know if it has helped you.

这篇关于Play Framework 2.0的Anorm上的Joda DateTime字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆