Hibernate + Joda Time: Auto Registering Type

OVERVIEW

Jadira Usertype is required when using Joda Time with Hibernate 4. The Joda Time objects are annotated accordingly in the Hibernate entity, and they looks something like this:-

@Entity
@Table(name = "person")
public class Person implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "personId")
    private Long id;

    @Column
    private String name;
	
    @Column
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
    private LocalDate birthDate;

    @Column
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    private LocalDateTime createdDatetime;
	
    // getters and setters
}

PROBLEM

This solution works, but it is rather tedious because I can never remember the actual @Type to write, thus I always end up copying and pasting it from past project code.

Further, that additional annotations clutter up my otherwise beautiful code.

SOLUTION

Jadira Usertype provides a clean way to auto register these Joda Time object types.

In the Hibernate configuration, add the following line:-

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>

    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="jadira.usertype.autoRegisterUserTypes">true</prop>
        </props>
    </property>
    <property name="packagesToScan">
        <list>
            <value>com.choonchernlim.project.entity</value>
        </list>
    </property>
</bean>

Now all @Type annotations can be safely removed from the Hibernate entity:-

@Entity
@Table(name = "person")
public class Person implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "personId")
    private Long id;

    @Column
    private String name;
	
    @Column
    private LocalDate birthDate;

    @Column
    private LocalDateTime createdDatetime;
	
    // getters and setters
}

Advertisements

One thought on “Hibernate + Joda Time: Auto Registering Type

  1. Pingback: Spring Boot: using Joda Time on JPA entity with Hibernate | Netgloo Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s