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.

7 comments:

  1. very useful information. thanks

    ReplyDelete
  2. والنظافة الان من الامور المهمة والاساسية فى حياة كل شخص ومعنا
    شركة تنظيف منازل بالجبيل هى شركة من اهم شركات التنظيف بالمنطقة وذلك لكونها تمتلك احدث المعدات الخاصة بالتنظيف وتتميز كذلك

    شركة تسليك مجارى بسيهات
    شركة تنظيف منازل بسيهات

    ReplyDelete
  3. However, such custom solutions are often cost inhibitive for SMEs, who mostly use the generic options of database transaction solutions provided with a standard database software package.kpi dashboards

    ReplyDelete
  4. Restrictions to database access: When the database of a company is controlled via the internet, this measure is at its best use.create dashboard for oracle

    ReplyDelete