Search code examples
grailsgrails-orm

Special Datatypes used in Domain Classes


Imagine for example you want to store amounts of money in a domain class. A simple approach would be something like this:

class Account {
    BigDecimal amount
}

but what if you don't want to handle your amount as simple BigDecimal but as Money type on which you have for instance defined some additional convenience methods like currency conversions.

So something like

class Account {
    Money amount
}

would result in getting it stored in another table.

So my question is: how can I define a class Money which would be stored as BigDecimal in the database?


Solution

  • You could use an embedded class to have an seperate Money class which is stored within your Account table.

    class Account {
        Money amount
        static embedded = ['amount']
    }
    
    class Money {
        BigDecimal amount
    
        def asDollar() {
            amount
        }
    
        def asEuro() {
            amount / 1.3
        }
    }
    

    Put both classes (Account and Money) into one groovy file within your domain folder to avoid the creation of an extra table for money.

    Another approach would be to use a custome hibernate type.