Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting Joda DateTime instead of Java Date in Hibernate

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 having to convert my Dates into Joda DateTime objects and back again.

So I was wondering, is there any reason I shouldn't just change my entities to store Joda DateTime objects instead of Java Date objects?

Please note that these entities are persisted via Hibernate. I found the jodatime-hibernate project, but I also was reading on the Joda mailing list that it wasn't compatible with newer versions of hibernate. And it seems like it isn't very well maintained.

So I'm wondering if it would be best to just continue converting between Date and DateTime, or if it would be wise to start persisting DateTime objects. My concern is being reliant on a poorly maintained library.

Edit: Note that one of my objectives is to be better able to store timezone information. Storing just a Date appears to save the date in the local timezone. As my application can be used globally, I need to know the timezone as well. Joda Time Hibernate seems to address this as well in the user guide.

like image 557
Tauren Avatar asked Feb 03 '10 02:02

Tauren


3 Answers

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.

like image 85
Chris Pheby Avatar answered Oct 31 '22 21:10

Chris Pheby


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).

like image 32
Jack Leow Avatar answered Oct 31 '22 23:10

Jack Leow


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.

like image 3
eh. Avatar answered Oct 31 '22 21:10

eh.