【问题标题】:How to set default value for Domain Class Values in Grails 2.2?如何在 Grails 2.2 中设置域类值的默认值?
【发布时间】:2013-05-06 12:54:05
【问题描述】:

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

class A {

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

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

但是没有任何效果。数据库中没有设置默认值。为了正确设置默认值,我必须进行哪些更改?

【问题讨论】:

    标签: grails grails-2.0 grails-domain-class


    【解决方案1】:

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

    Class A {
          Long someValue 
          Long someOtherValue
    
          Boolean someBool
          Boolean someOtherBool
    
         static mapping = {
            someOtherValue defaultValue: 1
            someOtherBool  defaultValue: true  
            ...
         } 
    
    }
    

    【讨论】:

    • 这是我写的问题。我使用 Grails 2.2.2 但它不工作。
    • 这适用于 2.3.6 中的所有类型,但不适用于 Boolean。我试过defaultValue: 'true'defaultValue: true。但表中填满了null。我必须使用Boolean mycolumn = Boolean.TRUE
    • 你的数据库是什么?
    • 使用 grails 2.5 和 mysql 5.6,似乎不可能为布尔值或布尔值设置数据库级别的 defaultValue。 true, 'true', "true", 1, '1', "1", Boolean.TRUE - 这些都不适用于静态映射部分。
    【解决方案2】:

    我发现要让 defaultValue 与 String 属性一起使用,我需要在单引号周围加上双引号,而要让 defaultValue 为数字属性工作,我需要在数字周围加上双引号,否则默认值不会出现在DDL。所以,例如:

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

    此外,据我所知,默认值不适用于枚举属性。

    【讨论】:

    • 遗憾的是,这不适用于布尔值(它是长度为 1 的 BIT 字段)。
    【解决方案3】:
    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 中测试。

    【讨论】:

    • 我还必须在 2.3.6 中设置这样的布尔列,在映射中为布尔列设置 defaultValue 不起作用。
    • 以上在 grails 2.5 和 mysql 中对布尔值不起作用,始终不提供默认值。
    • 在 Grails 3.3 defaultValue: falsedefaultValue:"'false'"defaultValue: 'false' 中的 MySQL 中也不起作用
    猜你喜欢
    • 2012-11-14
    • 2013-12-10
    • 2012-05-14
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 2014-10-31
    相关资源
    最近更新 更多