Persist Joda-time's DateTime via Hibernate

喜夏-厌秋 提交于 2019-12-17 22:21:35

问题


I'm using Jodatime in my Play app, but currently having to do a bunch of converting back and forth from/to java.util.Date and java.sql.Time.

Since jodatime is included in the Play distribution, I'm thinking there's probably a better way to do this. Is there any way I can make my Model fields DateTimes instead of java.util.Date and java.sql.Time so the conversion is done automatically? Is there another way of streamlining this?


回答1:


For Hibernate 3 add the following annotation to your date field:

@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")

Hibernate will now do the dirty work for you.

(Make sure you have joda-time-hibernate.jar in your classpath)

UPDATE:

For Hibernate 4 and 5 add the following annotation:

@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")

(Make sure you have jadira-usertype-core.jar in your classpath)




回答2:


  1. Joda recommends to use the UserType libraries with Hibernate 4.0, the version of Hibernate bundled with Play 1.2.x (see: http://joda-time.sourceforge.net/contrib/hibernate/index.html).

  2. The proper way to handle the dependency is using the dependencies.yml file, including a line like this:

    - org.jadira.usertype -> usertype.jodatime 2.0.1
    



回答3:


Instead of putting the @Type annotation at each of your Joda properties you can add this in your jpa properties

#Hibernate config
jadira.usertype.autoRegisterUserTypes=true

and it should work just fine.

ps. jadira-usertype-core.jar should be in your classpath.




回答4:


We should enable two jars in Hibernate 4 project:

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


来源:https://stackoverflow.com/questions/6284098/persist-joda-times-datetime-via-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!