2013-05-12 120 views
6

在我的Grails領域類中,我想設置保留在數據庫中的默認值。我使用mysql作爲數據庫。我試圖做到這一點:如何在Grails 2.2中爲域類值設置默認值?

class A { 

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

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

但沒有任何工作。數據庫中沒有設置默認值。爲了讓我的默認值設置正確,我需要更改哪些內容?

回答

6

如果你在上面的Grails 2.2上,那麼你可以使用defaultValue。看看伯特的答案here 試試吧,希望這有助於:

Class A { 
     Long someValue 
     Long someOtherValue 

     Boolean someBool 
     Boolean someOtherBool 

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

} 
+0

這是我寫的問題。我使用Grails 2.2.2,但它不工作。 – confile 2013-05-12 15:06:29

+1

這適用於所有類型的2.3.6,但不適用於'Boolean'。我嘗試了'defaultValue:'true''和'defaultValue:true'。但是在表中被填充了'null'。我必須使用布爾mycolumn = Boolean.TRUE' – Guus 2014-04-11 14:51:44

+0

什麼是您的數據庫? – Alidad 2014-04-11 15:06:19

2

我發現,對於默認值與字符串性質的工作,我需要把周圍的單引號雙引號和默認值,爲數值屬性的作用,我需要在數字周圍加雙引號,或者默認值不會出現在DDL中。所以,舉例來說:

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

而且,據我所知,默認值不爲是枚舉屬性的作用。

+0

不幸的是,這不適用於布爾(長度爲1的BIT字段)。 – 2015-08-07 09:13:02

2
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中測試。

+0

我還必須在2.3.6中爲布爾列設置defaultValue映射中的布爾列不起作用。 – Guus 2014-04-11 14:52:45

+0

上面的代碼不適用於我們在布爾值的grails 2.5和mysql中,總是沒有默認值。 – 2015-08-07 09:09:17

+0

在Grails 3.3的'defaultValue:false'或'defaultValue:'''''或'defaultValue:'false''中也不起作用 – Guus 2017-09-08 06:26:05