2013/06/29

Grails enum custom database value mapping

About

How to map a custom value and type of enum constants into database with Grails Domain.

TL;DR

Just add id field to the enum class and set its value for each enum constant.

Example case

When modelling domain there is often some enum domain class introduced. Such as WhateverType or SomethingsStatus. Let say we want to use ordinal instead of default GORM's text mapping.
class SomeDomainElement {
    Level level

    static mapping = {
        level enumType: 'ordinal'
    }
}
Our enum presents itself as follows:
enum Level {
    EASY,
    MEDIUM,
    HARD
}
Latter introduction of a new level may happen. Lest say ADVANCED. It would be really tempting to place such between levels MEDIUM and HARD. This however would have changed the position number of level HARD. Stop! Database mapping will change either. What about already stored 'levels HARD'?

Solution

Remove the mapping block from SomeDomainElement. It won't be needed any more. Just add the id field to the enum constants.
enum Level {
    EASY(1),
    MEDIUM(2),
    ADVANCED(4),
    HARD(3)

    final int id
    private Level(int id) { this.id = id }
}
The field must be named id so Grails would map it automatically as DB value.

Any serializable and known by Hibernate type can be used instead of int. Like char, String, BigDecimal, Date and so on.

4 comments: