Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the precision of BigDecimal in Grails

I'm using BigDecimal in domains as type. If I check the generated schema in the database (mySql), the column type is decimal(19,2). I can change it by using constraints in the Domain class ( as decribed in Grails documentation) like:

static constraints = {
     salary (scale: 3, maxSize:32)
}

My question is: how to define the scale and maxSize for all fields of type BigDecimal in my application?

I have already tried to define it in the config.groovy like that

grails.gorm.default.constraints = {
    '*'(scale:10, size:32, class:BigDecimal)
}

or like that:

grails.gorm.default.mapping = {
    '*'(scale:10, size:32, class:BigDecimal)
}

Unfortunately it doesn't work.

Grails vesion is 2.2.2.

like image 334
Waldemar Avatar asked Jan 09 '14 14:01

Waldemar


2 Answers

The scale constraint allows you to control this:

...
BigDecimal myNum

static constraints = {
   myNum(scale: 6)
}
...

http://grails.org/doc/latest/ref/Constraints/scale.html

like image 129
Sridhar.jindam Avatar answered Nov 12 '22 05:11

Sridhar.jindam


The best way i found to do this is the following:

In your Config.groovy you define the following:

grails.gorm.default.constraints = {
  myCustomScale( scale: 10, max: 9999999999999999999999.99999999 )
}

In your Domain Object you add the following contraint:

static constraints = {      
  myField shared: 'myCustomScale'
}

You can use this contraint for all your BigDecimal fields where needed. If you need to adjust the scale (lets say for a specific customer) you can control this by changing it in the config.

Hope this helps

like image 42
Oliver Avatar answered Nov 12 '22 06:11

Oliver