【问题标题】:Persist Joda-time's DateTime via Hibernate通过 Hibernate 持久化 Joda-time 的 DateTime
【发布时间】:2011-09-11 03:55:08
【问题描述】:

我在我的 Play 应用中使用 Jodatime,但目前不得不在 java.util.Datejava.sql.Time 之间来回转换。

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

【问题讨论】:

    标签: hibernate jodatime


    【解决方案1】:

    对于 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

    【讨论】:

    • 我添加了它并导入了org.hibernate.annotations.Type,但得到“无法确定类型:org.joda.time.contrib.hibernate.PersistentLocalDate`”。还有什么我需要设置的吗?或者可能是 Play 仅通过 JPA 而不是直接使用 Hibernate 的问题?
    • 您应该在类路径中包含 joda-time-hibernate jar。
    • 将 jar 放到 framework/lib 中,重新启动,并且能够使其正常工作。他们的网站起初确实欺骗了我,“获取最新版本”的大链接是针对 joda-time,而不是 joda-time-hibernate。
    • 有什么理由不使用org.joda.time.contrib.hibernate.PersistentDateTime,因为这是要求的数据类型?如果您使用它,也可以让该字段使用固定装置,因为有一个用于DateTime 但没有LocalDate 的活页夹。
    • @KeesdeKooter ,该问题要求 JPA 解决方案。您的答案使用@Type(...)。我猜你的意思是 org.hibernate.annotations.Type 。使用这个注解会创建对 Hibernate 的依赖。你知道使用更通用的 JPA 代替 Hibernate 的解决方案吗?
    【解决方案2】:
    1. Joda 建议将 UserType 库与 Hibernate 4.0(与 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
      

    【讨论】:

    • 我建议您为此打开一个新问题。
    【解决方案3】:

    您可以将其添加到您的 jpa 属性中,而不是将 @Type 注释放在您的每个 Joda 属性中

    #Hibernate config
    jadira.usertype.autoRegisterUserTypes=true
    

    它应该可以正常工作。

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

    【讨论】:

    • 这个解决方案减少了对 Hibernate 特定注解的依赖。不错!
    【解决方案4】:

    我们应该在 Hibernate 4 项目中启用两个 jar:

    • 编译("joda-time:joda-time:2.8")
    • 编译("org.jadira.usertype:usertype.jodatime:2.0.1")

    【讨论】:

      猜你喜欢
      • 2011-01-12
      • 2014-05-12
      • 2012-01-07
      • 2014-02-25
      • 2023-04-09
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多