How to Map Dates with Hibernate – Use joda-time

September 5, 2011

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 solution:

The user guide is pretty clear:

@Column
@Type(type="........PersistentDateTime")
private DateTime fromDate;

However, there’s might be issues with these libraries when hibernate version change. For that reason you may need to extend the PersistentDateTime class and use your own class in the @Tpe mapping.

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.

3 Responses to “How to Map Dates with Hibernate – Use joda-time”

  1. Hello
    It is posible to define this type into xml config or something like properties ?

  2. You can define that a field is of that type (http://learningviacode.blogspot.com/2011/09/creating-hibernate-custom-type-4.html), but you need to have the java class on the classpath to use it.

  3. @Entity
    @Table(name = “cm_cash_master”)
    public class Cash {
    private DateTime cm_date;
    @Column(name = “CM_DATE”)
    @Type(type = “org.joda.time.contrib.hibernate.PersistentDateTime”)
    public DateTime getCm_date() {
    return cm_date;
    }

    public void setCm_date(DateTime cm_date) {
    this.cm_date = cm_date;
    }

    @Transient
    public String getCashDateString() {
    String birthDateString = “”;
    if (cm_date != null)
    birthDateString = org.joda.time.format.DateTimeFormat.forPattern(“yyyy-MM-dd”).print(cm_date);
    return birthDateString;
    }

    }

    when i run this code .i found following error during runtime

    org.hibernate.MappingException: Could not determine type for: org.joda.time.contrib.hibernate.PersistentDateTime, at table: cm_cash_master, for columns: [org.hibernate.mapping.Column(CM_DATE)]

Leave a Reply