简体   繁体   English

如何在Grails 2.2中为Domain Class Values设置默认值?

[英]How to set default value for Domain Class Values in Grails 2.2?

In my Grails domain class I want to set default values which do persist in the database. 在我的Grails域类中,我想设置在数据库中保留的默认值。 I use mysql as database. 我使用mysql作为数据库。 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? 我需要更改什么才能正确设置默认值?

If you are on Grails 2.2 above then you can use defaultValue. 如果您使用的是上面的Grails 2.2,那么您可以使用defaultValue。 Look at Burt's answer here Try it, hope this helps: 看看Burt的答案在这里尝试一下,希望这会有所帮助:

Class A {
      Long someValue 
      Long someOtherValue

      Boolean someBool
      Boolean someOtherBool

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

}

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. 我发现defaultValue使用String属性,我需要在单引号周围加双引号,defaultValue用于数字属性,我需要在数字周围放置双引号,否则默认值不会出现在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. 另外,据我所知,默认值不适用于枚举属性。

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. 这将工作,在2.2.3中测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM