How to save object in grails

71 Views Asked by At

I have grails 2.0.4 app, I have new domain class as below, which contains around 50 properties

class Test{
  int testField1
  int testField2
  int testField2
   .
   .
  int testFieldN
}

And I want to do as follows,

 Display Value         Value to Save in DB

'Excellent'             10
'Good'                  8
'Average'               6
'Poor'                  4
'Pathetic'              2

I have a html form which contains all these properties.

If testField1 value is any of the value of "Display Value" then the value to be saved will be the corresponding value listed in "Value to Save in DB"

For example If testField1 value is 'Excellent' then value to be saved is 10.

This particular mapping applies to around 30 properties in the domain class.

Like this I have different mappings for different properties.

How to achieve this in grails.

1

There are 1 best solutions below

0
On

I suggest to use enums.

class Test{
  enum Scales{ 
    Excellent(10), Good(8), Average(6), Poor(4), Pathetic(2)
    private final int value
    Scales(int v){ this.value = v}
    int getValue(){ this.value}
  }

  int testField1
  int testField2
  int testField2
   .
   .
  int testFieldN
} 

GSP

<g:select name='testField1' from="${Test.Scales}" optionKey="value"/>

But better use enum as a type of property

class Test{
  enum Scales{ 
    Excellent(10), Good(8), Average(6), Poor(4), Pathetic(2)
    private final int value
    Scales(int v){ this.value = v}
    int getValue(){ this.value}
  }

  Scales testField1 
  ....
}

and then GSP

<g:select name='testField1' from="${Test.Scales}"/>