通过Hibernate坚持Joda-time的DateTime

Bra*_*ace 42 hibernate jodatime

我在我的游戏应用程序中使用Jodatime,但目前不必做来回转换自/至一束java.util.Datejava.sql.Time.

由于jodatime包含在Play发行版中,我认为可能有更好的方法来实现这一点.有没有什么办法可以让我的模型字段DateTimes,而不是java.util.Datejava.sql.Time这样的转换是自动完成的?还有另一种简化方法吗?

Kee*_*ter 53

对于Hibernate 3,在日期字段中添加以下注释:

@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
Run Code Online (Sandbox Code Playgroud)

Hibernate现在将为您完成肮脏的工作.

(确保你的类路径中有joda-time-hibernate.jar)

更新:

对于Hibernate 4和5,添加以下注释:

@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
Run Code Online (Sandbox Code Playgroud)

(确保在类路径中有jadira-usertype-core.jar)

  • 我添加了它并导入了`org.hibernate.annotations.Type`但得到“无法确定类型:org.joda.time.contrib.hibernate.PersistentLocalDate`”。我还需要设置什么吗?或者可能是 Play 仅通过 JPA 而不是直接使用 Hibernate 的问题? (2认同)
  • 您应该在类路径中包含joda-time-hibernate jar. (2认同)
  • @KeesdeKooter,问题是JPA解决方案.你的答案使用@Type(...).我猜你的意思是org.hibernate.annotations.Type.使用此注释会创建对Hibernate的依赖.您是否知道使用更一般的JPA而不是Hibernate的解决方案? (2认同)

Sam*_*uel 10

  1. Joda建议将UserType库与Hibernate 4.0一起使用,Hibernate是与Play 1.2.x捆绑在一起的Hibernate版本(参见:http://joda-time.sourceforge.net/contrib/hibernate/index.html).

  2. 处理依赖项的正确方法是使用该dependencies.yml文件,包括如下所示的行:

    - org.jadira.usertype -> usertype.jodatime 2.0.1
    
    Run Code Online (Sandbox Code Playgroud)


naX*_*aXa 7

@Type您可以在jpa属性中添加注释,而不是在每个Joda属性上添加注释

#Hibernate config
jadira.usertype.autoRegisterUserTypes=true
Run Code Online (Sandbox Code Playgroud)

它应该工作得很好.

PS. jadira-usertype-core.jar应该在你的类路径中.

  • 该解决方案减少了对Hibernate特定注释的依赖。真好! (2认同)