在Grails Domain Class中为Date字段设置默认值 [英] Setting default value for Date field in Grails Domain Class

查看:238
本文介绍了在Grails Domain Class中为Date字段设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为Domain类中的 Date 字段设置默认值。

I'm trying to set a default value for a Date field in a Domain class.

I可以在映射配置中使用 defaultValue ,但它不适用于 Date 字段(我试过它在字符串整数,它工作正常)。

I can use defaultValue in the mapping configuration but it doesn't work with Date fields (I've tried it on String and Integer and it works fine).

这是一个例子:

This is an example:

class Something {

    Date myField

    static mapping = {
        myField defaultValue: new Date()
    }

}

此代码失败,因为Hibernate生成的CREATE语句不正确。它是这样的:

This code fails because the CREATE statement that Hibernate generates is incorrect. It is something like:

... my_field datetime default Mon Nov 25 17:59:08 UYST 2013 not null ...


推荐答案

您可以始终初始化静态初始化程序中的字段或设置构造函数中的值:

You can always initialize the field in the static initializer or set the value in the constructor:

class Something {
    // initializer
    Date myField = new Date()

    // or in the ctor
    Something() {
        myField = new Date()
    }
}

这不会在数据库模式中设置默认值,它只会在创建实例时设置字段的值。如果您希望模式具有默认值,您可以像下面这样使用'defaultValue'映射条目:

This doesn't set a default value in the database schema, it merely sets the value of the field on creation of the instance. If you want the schema to have a default value, you can use the 'defaultValue' mapping entry like so:

class Something {
    Date myField

    static mapping = {
        myField defaultValue: "now()"
    }
}

您为默认值设置的值取决于您的数据库供应商。 (注意使用sql now()方法而不是Java / Groovy new Date()

the value you set for the default value is dependent on your database vendor. (notice the use of sql now() method rather than Java/Groovy new Date().

这篇关于在Grails Domain Class中为Date字段设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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