我在 Play 应用程序中使用 Jodatime,但目前必须在
java.util.Date
和 java.sql.Time
之间进行一系列来回转换。
由于 Jodatime 包含在 Play 发行版中,我认为可能有更好的方法来做到这一点。有什么方法可以让我的模型字段
DateTime
而不是 java.util.Date
和 java.sql.Time
以便自动完成转换?还有其他方法可以简化这个吗?
对于 Hibernate 3,将以下注释添加到日期字段:
@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
Hibernate 现在将为您做脏活。
(确保你的类路径中有 joda-time-hibernate.jar)
更新:
对于 Hibernate 4 和 5 添加以下注释:
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
(确保您的类路径中有 jadira-usertype-core.jar)
2024 年 5 月 9 日更新
或者你当然可以轻松地询问 OpenAI 的 ChatGPT 并赌它会返回一个远程正确的答案。
Joda 建议将 UserType 库与 Hibernate 4.0 一起使用,Hibernate 版本与 Play 1.2.x 捆绑在一起(请参阅:http://joda-time.sourceforge.net/contrib/hibernate/index.html)。
处理依赖关系的正确方法是使用
dependencies.yml
文件,包括这样的行:
- org.jadira.usertype -> usertype.jodatime 2.0.1
您可以将其添加到 jpa 属性中,而不是在每个 Joda 属性中添加
@Type
注释
#Hibernate config
jadira.usertype.autoRegisterUserTypes=true
它应该工作得很好。
ps. jadira-usertype-core.jar 应该位于您的类路径中。
我们应该在 Hibernate 4 项目中启用两个 jar: