Always Get Better

Never stop looking for ways to improve

May 20th, 2012

Which data type should you use for time information on your Java models? The Date class is mostly deprecated, pushing us into the direction of the heavyweight Calendar class. Storing the milliseconds since Epoch in a Long is both database-friendly and easy to perform math on and convert at runtime. But if you really want a good experience, you are using Joda Time.

Joda Time is built into the Play! Framework, and there really is no excuse to use anything else. But when it comes to saving dates in your JPA Models, there is a big “gotcha” in that there is no default type converter to move a DateTime object into and out of the database. Oops.

But that can be fixed with an annotation in your model, like this:

@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
public DateTime created;

Unfortunately, Play does not ship with Hibernate support for the DateTime object. So to make this work you need to include the Joda-Time-Hibernate library in your dependencies.yml file:


require:
- play
- joda-time -> joda-time-hibernate 1.3

After updating the dependencies file, run the play deps –sync command to pull in the libraries from maven. Your models will now save their date and time into MySQL, and your programming experience will be smooth as silk – at least as far as time-based functionality is concerned.

  • Mike Wilson (166)
  • 3 Responses to “ Using DateTime in the Play! Framework ”

    1. Joda-Time-Hibernate is now almost deprecated in favour of the external usertype project – http://usertype.sourceforge.net/

    2. Mike says:

      Unfortunately the usertype project doesn’t play nice (ha! see what I did there?) with the JPA/hibernate version that ships with Play. As the framework catches up, we can use their excellent dependency management system to upgrade to usertype. In the meantime this method works right out of the box.

    3. [...] Using DateTime in the Play! Framework [...]

    Leave a Reply