Mapping JodaTime properties using JPA and custom UserTypes

JPA does not natively support mapping custom types to table columns. If you’re using Hibernate as your JPA provider then it does support custom UserTypes to provide mappings beyond the normal String to varchar, and other simple types.

For using the JodaTime’s DateTime, there’s a couple of options:

  • Joda Time Hibernate is a Hibernate contributed library (http://joda-time.sourceforge.net/contrib/hibernate/index.html)
  • UserType for Hibernate looks like it is an updated version of Joda Time Hibernate,   adds support for JSR310 (the new JDK Date implementation based on JodaTime), while also keeping backwards compatibility with Joda Time Hibernate

I tried UserType for Hibernate first, but got errors on a Roo generated @RooEntity:

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

I got this trying to persist:

java.lang.AbstractMethodError: org.jadira.usertype.dateandtime.joda.PersistentDateTime.nullSafeSet(Ljava/sql/PreparedStatement;Ljava/lang/Object;I)V
at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:140)

I’m not sure what this is about so switched the type to the Joda Time Hibernate library, and got it to work as expected straight away:

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