Play Framework 2.0的Anorm上的Joda DateTime字段 [英] Joda DateTime Field on Play Framework 2.0's Anorm
问题描述
我一直在学习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?
推荐答案
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屋!