Persisting Joda DateTime instead of Java Date in Hibernate

前端 未结 4 1763
一整个雨季
一整个雨季 2021-02-05 13:22

My entities currently contain java Date properties. I\'m starting to use Joda Time for date manipulation and calculations quite frequently. This means that I\'m constantly hav

相关标签:
4条回答
  • 2021-02-05 13:52

    I think using the Joda DateTime as your bean property type is probably a good idea. You can then have Hibernate do the conversion and save the property as the native database date format.

    I have personally used jodatime-hibernate and have not had a problem with it (we're using Hibernate 3.2.5GA).

    If you have concerns about jodatime-hibernate, you can always use Hibernate's custom type mapping mechanism (which I'm sure is all jodatime-hibernate does).

    0 讨论(0)
  • 2021-02-05 13:53

    Joda Time Hibernate can be used with recent Hibernate releases - you may need a little bit of tweaking your dependency graph thats all (e.g. setting exclusions). Can I also suggest you look at User Type, which I have released onto Sourceforge. This provides User Types for Joda Time which aim to avoid the client offset issue you mentioned. I would welcome any feedback you have on that project. https://sourceforge.net/projects/usertype/files/

    Regards Chris.

    0 讨论(0)
  • 2021-02-05 13:55

    Dates shouldn't be stored using a high level of abstraction like, say, a string ("2009-08-07 07:43:19 ...") nor as Java objects. They should be persisted as milliseconds since the epoch. Both Joda time and the regular Java date time can give you the time in milliseconds since the epoch. Store the number of milliseconds elapsed and convert back to objects when you're reading back from your DB.

    Persisting heavyweight Date objects instead of a long is a bit like using floating point numbers to represent monetary amounts: it's typically a huge code smell.

    0 讨论(0)
  • 2021-02-05 13:59

    So, to sum it up:

    java.util.Date

    • + native support in Hibernate
    • – bad API

    Joda-Time

    • + better API
    • – lack of native support in Hibernate

    Personally, if I could keep the domain model and "service layer" clean by just using a third party library (apparently User Type for Hibernate in this case) and the alternative would be to write some extra code to do the conversion "manually" every time it was needed, I'd go with the third party library.

    0 讨论(0)
提交回复
热议问题