简体   繁体   English

如何在Grails域类中正确设置属性值

[英]How to Properly Set Property Value in Grails Domain Class

Just doing some testing and Google searching and ran across a suggestion stating that you should set the defaultValue parameter in the mapping for a property if you want to set a default value. 只是进行了一些测试和Google搜索,然后遇到了一条建议,指出如果要设置默认值,则应在属性的映射中设置defaultValue参数。 Originally I had it set like so: 最初,我将其设置为:

property = value

I can see the values set in the database as per my defaults. 我可以按照默认设置查看数据库中设置的值。 When I switched it to this: 当我切换到这个:

static mapping = {
    property defaultValue: value
}

So at this point I have both set like the examples above and was wondering if I really needed that. 因此,在这一点上,我都设置了上面的示例,并且想知道我是否真的需要这样做。 It was working fine for me without the mappings, but maybe the mappings do something else that i'm not yet aware of. 没有映射,对我来说一切正常,但是映射可能会做我还不知道的其他事情。

It depends on your expected behavior of your application. 这取决于应用程序的预期行为。 Both are valid, and work perfectly fine. 两者都是有效的,并且工作得很好。

The first, by assigning a default on the property of the domain class will not only set a default at the database schema level but provide a default on a new instance of your domain class. 首先,通过在域类的属性上分配默认值,不仅将在数据库架构级别设置默认值,还将在您的域类的新实例上提供默认值。

The second, by setting a default value within the mappings closure will only set a default at the database schema level. 第二个,通过在映射关闭中设置默认值,只会在数据库模式级别设置默认值。

So, depending on how you expect a new instance of your domain class to behave you have a choice. 因此,根据您期望域类的新实例的行为方式,您可以选择。 Default at the instance and database schema level, or just at the database schema level. 在实例和数据库架构级别,或者仅在数据库架构级别,为默认值。

The choice is yours. 这是你的选择。 Flexibility. 灵活性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM