How to set default value for Domain Class Values in Grails 2.2?
Solution 1
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
...
}
}
Solution 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.
Solution 3
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.
confile
Java, GWT, JavaScript, Grails, Groovy, Swift, Objective-C, iOS
Updated on June 23, 2022Comments
-
confile almost 2 years
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?
-
confile almost 11 yearsthis is what I wrote as question. I use Grails 2.2.2 but it is not working.
-
A.W. about 10 yearsThis works for in 2.3.6 for all types but not for
Boolean
. I trieddefaultValue: 'true'
anddefaultValue: true
. But in the table is is filled withnull
. I have to useBoolean mycolumn = Boolean.TRUE
-
A.W. about 10 yearsI also have to set boolean columns like this in 2.3.6 Setting defaultValue for a boolean columnn in the mappings does not work.
-
Alidad about 10 yearswhat is your database ?
-
John Little over 8 yearsThe above does not work for us in grails 2.5 and mysql for booleans, always gives no default.
-
John Little over 8 yearsSadly, this does not work for booleans (which are BIT fields with length of 1).
-
John Little over 8 yearsUsing 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.
-
A.W. over 6 yearsAlso does not work in MySQL in Grails 3.3
defaultValue: false
ordefaultValue:"'false'"
ordefaultValue: 'false'