How can i set default value in grails domain class

后端 未结 3 1392
遥遥无期
遥遥无期 2021-02-05 00:27

Is there any way to set a default value to domain class property? I have a class called PayMethod, where I want the name property to default to \

相关标签:
3条回答
  • 2021-02-05 00:30

    Had the same issue and using static mapping didn't work for me either (using 2.2.3); the below link provided me a functional answer (set the default value in your object declarations):

    http://grails.1312388.n4.nabble.com/How-to-set-a-default-value-for-column-td1383753.html

    For String, encapsulate with quotes; int/integer should just be the value.

    Hope this helps!

    0 讨论(0)
  • 2021-02-05 00:39

    This will be possible in 2.2 which should be released this week or next. See http://jira.grails.org/browse/GRAILS-5520 for the relevant feature request. The syntax will be

    static mapping = {
       name defaultValue: "'Cash'"
    }
    

    For now you'll need to do what you're doing - set the value as the default value of the field. You can manually update the database schema, or do the work as part of a migration.

    0 讨论(0)
  • 2021-02-05 00:52

    To build on the previous answer, you can use the defaultValue attribute in Grails 2.2 but you need to be careful to put double and single quotes around default values for String properties and double quotes around integer properties so that the default values appear correctly in the DDL. So, for instance, you need to use:

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

    If you only use single quotes, you will end up with an error like "Column "CASH" not found" Also, as far as I can tell, default values do not work for properties that are enums.

    0 讨论(0)
提交回复
热议问题