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;

3 Replies to “Mapping JodaTime properties using JPA and custom UserTypes”

  1. Hi Kev,

    Which version of Usertype are you using? The last version that works with Hibernate versions prior to Hibernate 4.x is 1.9.1 – the error you have suggests you have picked up a later version.

    Thanks Chris

  2. Ah, ok, that would explain it…. I’m using Hibernate 3.6.4, and looks like I pulled in version 3.0.0.0.CR1 of usertype.core – I’ll try 1.9.1 and see if that works for me.

    Thanks for the tip!

  3. Did you manage to get Roo’s validation to output a user-friendly error message? If I type “1/2” as the date, I get:

    Failed to convert property value of type java.lang.String to required type org.joda.time.LocalDate for property birthDate; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.validation.constraints.NotNull @org.hibernate.annotations.Type @org.springframework.format.annotation.DateTimeFormat org.joda.time.LocalDate for value 1/2; nested exception is java.lang.IllegalArgumentException: Invalid format: "1/2" is too short

Leave a Reply to Daniel Serodio Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.