6

In my Grails domain class I want to set default values which do persist in the database. I use mysql as database. I tried to do this:

class A {

   long someValue = 1
   long someOtherValue
   boolean someBool = true
   boolean someOtherBool

   static mapping = {
      someOtherValue defaultValue: 1
      someOtherBool defaultValue: true  
   }
}

But nothing works. There are no default values set in the database. What do I have to change to get my default values being set correctly?

Michael
  • 32,527
  • 49
  • 210
  • 370

3 Answers3

6

If you are on Grails 2.2 above then you can use defaultValue. Look at Burt's answer here Try it, hope this helps:

Class A {
      Long someValue 
      Long someOtherValue

      Boolean someBool
      Boolean someOtherBool

     static mapping = {
        someOtherValue defaultValue: 1
        someOtherBool  defaultValue: true  
        ...
     } 

}
Community
  • 1
  • 1
Alidad
  • 5,463
  • 1
  • 24
  • 47
  • this is what I wrote as question. I use Grails 2.2.2 but it is not working. – Michael May 12 '13 at 15:06
  • 1
    This works for in 2.3.6 for all types but not for `Boolean`. I tried `defaultValue: 'true'` and `defaultValue: true`. But in the table is is filled with `null`. I have to use `Boolean mycolumn = Boolean.TRUE` – A.W. Apr 11 '14 at 14:51
  • what is your database ? – Alidad Apr 11 '14 at 15:06
  • Using grails 2.5, and mysql 5.6, it does not seem possible to set a database level defaultValue for a boolean nor a Boolean. true, 'true', "true", 1, '1', "1", Boolean.TRUE - none of these work in the static mapping section. – John Little Aug 07 '15 at 09:59
2

I found that for defaultValue to work with String properties, I needed to put double quotes around single quotes and for defaultValue to work for numeric properties, I needed to put double quotes around the number or the defaults wouldn't appear in the DDL. So, for instance:

static mapping = {
   myStringProperty defaultValue: "'Cash'"
   myIntProperty defaultValue: "0"
}

Also, as far as I can tell, default values do not work for properties that are enums.

Ed OConnor-Giles
  • 716
  • 6
  • 12
2
class A {

   long someValue
   long someOtherValue
   boolean someBool = Boolean.TRUE
   boolean someOtherBool = Boolean.TRUE

   static mapping = {
      someValue defaultValue: '1'
      someOtherValue defaultValue: '1'
   }
}

This will work, tested in 2.2.3.

MikeZoo
  • 23
  • 5
  • I also have to set boolean columns like this in 2.3.6 Setting defaultValue for a boolean columnn in the mappings does not work. – A.W. Apr 11 '14 at 14:52
  • The above does not work for us in grails 2.5 and mysql for booleans, always gives no default. – John Little Aug 07 '15 at 09:09
  • Also does not work in MySQL in Grails 3.3 `defaultValue: false` or `defaultValue:"'false'"` or `defaultValue: 'false'` – A.W. Sep 08 '17 at 06:26