我如何在grails域类中设置默认值 [英] How can i set default value in grails domain class

查看:212
本文介绍了我如何在grails域类中设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将默认值设置为域类属性?
我有一个名为PayMethod的类,我希望'name'属性默认为'cash'。当我创建这个表时,我想要这个默认值,这是可能使用约束?

Is there any way to set a default value to domain class property ? I have a class called as PayMethod, where I want the 'name' property to default to 'cash'. and i want this default value when i create this table, Is this possible using constraints ?

package abc

import util.UserUtil
import embed.AuditUser

class PayMethod {

    String name = "Cash"

    AuditUser audit = new AuditUser()
    static embedded = ['audit']    

    static constraints = {
        name blank: false, size: 5..30, unique: true
    }

    static mapping = {
        table 't01i0010'
        id column: 'F_ID', precision: 4, scale: 0
        name column: 'F_NAME', length: 30, defaultValue: 'Cash'
        version column: 'F_REVISION'
    }

    def authUserService
    int insertIndex = 0
    int updateIndex = 0
    static transients = ['authUserService', 'insertIndex', 'updateIndex']    

    def beforeInsert = {
        audit.entryUser = UserUtil.user()
        audit.entryDate = new Date();
    }

    def beforeUpdate = {
        audit.reviseUser = UserUtil.user()
        audit.reviseDate = new Date();
    }

    def afterInsert = {
        if(insertIndex == 0){
            def user = audit.entryUser
            def date = audit.entryDate
            log.info "POST INSERT => ENTERER: ${user} ENTERED: ${date}"
        }
        insertIndex++
    }

    def afterUpdate = {
        if(updateIndex == 0){
            def user = audit.reviseUser
            def date = audit.reviseDate
            log.info "POST UPDATE => REVISE: ${user} REVISED: ${date}"
        }
        updateIndex++
    }
}


推荐答案

2.2版可能会在本周或下周发布。有关相关信息,请参阅 http://jira.grails.org/browse/GRAILS-5520 功能要求。语法将为

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.

这篇关于我如何在grails域类中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆