Joda with JPA

I have to work with a few legacy databases that are used by several different apps (apparently the database is a perfect integration point), and I want to use the Joda api in my persistence. In this example the date is actually stored as a string, genius! I’m going to use LocalDate as the string doesn’t store the time element. If you are lucky enough and the database is actually storing date time check this post out Joda With DateTime

To start with a create a simple helper class that converts String to LocalDate and LocatDate to String

public static LocalDate createLocalDateForString(String dateString){
  DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
  return StringUtils.isEmpty(value) ? null :  fmt.parseDateTime(dateString).toLocalDate();	
    public static String createStringForLocalDate(LocalDate date){
    	return date.toString("yyyyMMdd"); 

Next is to create your own user type. This is done by implementing org.hibernate.usertype.UserType. The main methods I’m implement are

public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
		LocalDate result = null;
		String dateAsString = rs.getString(names[0]);
			result = StringUtils.isNotEmpty(dateAsString) ? DateHelper.createLocalDateForString(dateAsString) : null;
		return result;

public void nullSafeSet(PreparedStatement statement, Object value, int index)
			throws HibernateException, SQLException {
		if(value == null){
			statement.setNull(index, SQL_TYPES[0]);
			String dateAsString = DateHelper.createStringForLocalDate((LocalDate)value);
			statement.setString(index, dateAsString);

All that is left is to add the annotation to each of your entity properties that you want to use as LocalDate.

@org.hibernate.annotations.Type(type = "xxx.LocalDateUserType")

3 thoughts on “Joda with JPA

  1. Is there a way to do this with JPA? Looks like you are using hibernate directly rather than JPA

  2. Pingback: How to map Joda Times with Hibernate « NerdGerl

Comments are closed.