Fork me on GitHub

24 Jun 2010

Defaulting Joda Time Hibernate Types with Grails

Grails 1.2 added the ability to define default Hibernate mappings that apply to all GORM classes. It turns out this is incredibly useful if you're using Joda-Time types instead of java.util.Date in your domain objects. Previously you had to specify the Hibernate user type for every single field, like this:
import org.joda.time.*
import org.joda.time.contrib.hibernate.*

DateTime dateCreated
DateTime lastUpdated
LocalDate birthday

static mapping = {
    dateCreated type: PersistentDateTime
    lastUpdated type: PersistentDateTime
    birthday type: PersistentLocalDate
}
Now you can just add this to your Config.groovy once and do away with the type mappings in the individual classes:
grails.gorm.default.mapping = {
    "user-type" type: PersistentDateTime, class: DateTime
    "user-type" type: PersistentLocalDate, class: LocalDate
}
Correction: I had previously posted that the method call in the default mapping DSL could be anything, but on further investigation it turns out it has to be user-type. Apologies for the error.

I'll look into the possibility of the Joda-Time plugin doing this itself to make things even easier.

115 comments: