1

I need to persist a time duration e.g. 5 d 4 h

I was thinking of using a convertion (Duration / Calendar / Date class) where I than can persist it as a long (millisec) to the db (MySql). Like that I can easily convert and work with it.

Is this a good way to do this?

hmatar
  • 2,437
  • 2
  • 17
  • 27
Darth Blue Ray
  • 9,445
  • 10
  • 35
  • 48
  • This thread describes how to convert Dates to DB Date: http://stackoverflow.com/questions/1081234/java-date-insert-into-database – Archer Jan 14 '13 at 13:44
  • 1
    The problem isn't to persist a Date object to the db. Hibernate in this case wille solve this and persist without a problem a Date to the DB. I need to persist a duration. The user will give for example a day, hours and min and this duration will be persist into the db. As stated I would convert it to a long (as milli sec) and work with it from that. Just wondering if that is the best way to do this. – Darth Blue Ray Jan 14 '13 at 13:53
  • 2
    Not all DBs could store TimePeriod. So, I doubt there's a better way. Converting to millis and storing them seems a good choice. – Archer Jan 14 '13 at 13:54
  • Just store Date with time stamp when start and store end time too.. then we can calculate... Else please post your case...At what case you want it... – Kanagaraj M Jan 14 '13 at 13:56

2 Answers2

1

JodaTime (and forthcoming javax.time) provide a Duration class, and JPA providers such as DataNucleus JPA provide persistence for them out of the box without the need to play around with conversions.

DataNucleus
  • 15,497
  • 3
  • 32
  • 37
  • For what I know, also java has a duration class and for the moment I just want to stick to Hibernate :) – Darth Blue Ray Jan 14 '13 at 13:57
  • The Joda Time project also has it's own support classes for Hibernate - you can probably use this if your JPA provider is Hibernate, but I'm not sure. See http://joda-time.sourceforge.net/contrib/hibernate/index.html – GreyBeardedGeek Jan 14 '13 at 13:58
  • FWIW javax.xml.datatype.Duration is intended for use within XML docs, not for serious treatment of time. – DataNucleus Jan 14 '13 at 14:02
1

For the Hibernate 4.0 JPA provider, you can use the Usertype project to get JPA persistence for Joda Time classes, and then use the @Type annotation.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67