Over a million developers have joined DZone.
Silver Partner

How to Map Dates with Hibernate – Use joda-time

· Java Zone

The Java Zone is brought to you by Stormpath—offering a pre-built identity API for developers. Easily build powerful user management, authentication, and authorization into your web and mobile applications. Check out this tutorial to build a simple web app with Spring Boot and Spring Security in 15 minutes.

This is always a question – how to map temporal data in our hibernate entities – whether to use java.util.Date, java.util.Calendar or simply long. The correct answer is: neither of these. Use joda-time – the de-facto Java datetime API. Using it throughout the whole project is a no-brainer, but how to use it with hibernate – you can’t use @Temporal. Hibernate supports custom types, so there’s a little project that solves the issue – joda-time – hibernate support.

The user guide is pretty clear:

@Column
@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime fromDate;

However, there’s one issue with that library – it uses static final fields from hibernate, which requires recompilation if the version of hibernate changes (see here). For that reason you may need to extend the PersistentDateTime class, override the 2 methods that use the static final TIMESTAMP field, and copy the exact same code from the superclass.

Using joda-time throughout the whole project will save tons of headaches. So I strongly suggest the above mechanism to use joda-time in your hibernate entities as well.

 

From http://techblog.bozho.net/?p=499

The Java Zone is brought to you by Stormpath—offering a pre-built, streamlined user management API for building web and mobile applications. Learn how token authentication with JWTs (JSON Web Tokens) helps secure websites and avoids the pitfalls of using cookies and sessions.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}