How to set default value for Domain Class Values in Grails 2.2?
Asked Answered
C

3

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?

Claudetteclaudia answered 12/5, 2013 at 9:30 Comment(0)
P
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  
        ...
     } 

}
Pleiad answered 12/5, 2013 at 11:16 Comment(4)
this is what I wrote as question. I use Grails 2.2.2 but it is not working.Claudetteclaudia
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.TRUEBookmobile
what is your database ?Pleiad
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.Wakeful
G
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.

Gigigigli answered 12/7, 2013 at 20:7 Comment(1)
Sadly, this does not work for booleans (which are BIT fields with length of 1).Wakeful
J
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.

Jackiejackinoffice answered 9/1, 2014 at 21:33 Comment(3)
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.Bookmobile
The above does not work for us in grails 2.5 and mysql for booleans, always gives no default.Wakeful
Also does not work in MySQL in Grails 3.3 defaultValue: false or defaultValue:"'false'" or defaultValue: 'false'Bookmobile

© 2022 - 2024 — McMap. All rights reserved.