如何在Grails2.2中为域类值设置默认值?

如何在Grails2.2中为域类值设置默认值?,grails,grails-2.0,grails-domain-class,Grails,Grails 2.0,Grails Domain Class,在我的Grails域类中,我想设置默认值,这些默认值在数据库中保持不变。我使用mysql作为数据库。我试着这样做: class A { long someValue = 1 long someOtherValue boolean someBool = true boolean someOtherBool static mapping = { someOtherValue defaultValue: 1 someOtherBool defa

在我的Grails域类中,我想设置默认值,这些默认值在数据库中保持不变。我使用mysql作为数据库。我试着这样做:

class A {

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

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

但什么都不管用。数据库中没有设置默认值。要正确设置默认值,我需要做哪些更改?

如果您使用上面的Grails 2.2,那么可以使用defaultValue。看看伯特的回答 试试看,希望这有帮助:

Class A {
      Long someValue 
      Long someOtherValue

      Boolean someBool
      Boolean someOtherBool

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

}

我发现,要让defaultValue处理字符串属性,我需要在单引号周围加双引号;要让defaultValue处理数字属性,我需要在数字周围加双引号,否则默认值不会出现在DDL中。例如:

static mapping = {
   myStringProperty defaultValue: "'Cash'"
   myIntProperty defaultValue: "0"
}
此外,据我所知,默认值不适用于枚举属性

class A {

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

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

这将起作用,在2.2.3中测试。

这是我作为问题写的。我使用Grails2.2.2,但它不起作用。这适用于2.3.6中的所有类型,但不适用于
Boolean
。我尝试了
defaultValue:'true'
defaultValue:true
。但在表中,是用
null
填充的。我必须使用
Boolean mycolumn=Boolean.TRUE
您的数据库是什么?使用grails 2.5和mysql 5.6,似乎无法为布尔值或布尔值设置数据库级别的默认值。true、'true'、'true',1、'1','1',Boolean.true-这些在静态映射部分都不起作用。我还必须在2.3.6中设置类似的布尔列。在映射中为布尔列设置defaultValue不起作用。上述在grails 2.5和mysql中对布尔不起作用,总是不提供默认值。Grails 3.3中的MySQL也不适用
defaultValue:false
defaultValue:“false”
defaultValue:“false”
遗憾的是,这不适用于布尔值(长度为1的位字段)。