gpt4 book ai didi

grails - Grails用户定义类型的域类属性的默认值

转载 作者:行者123 更新时间:2023-12-02 14:41:32 24 4
gpt4 key购买 nike

我有一个域类计划,如下所示:

class Plan{
String name
static constraints={
name(unique:true,nullable:false)
}
}

另一个域类是User:
class User{
// Other attribures and code
// ....
Plan plan
static constraints = {
// other constraints..
plan(nullable:false, defaultValue: Plan.findByName("default"))
}
}

上面的代码给我错误:
Caused by: java.lang.IllegalStateException: Method on class [mypackage.Plan] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.
at mypackage.User$__clinit__closure1.doCall(User.groovy:31)

上面错误的行是
plan(nullable:true,defaultValue: Plan.findByName("default"))

我也在BootStrap.groovy中定义了默认计划:
if(!Plan.findByName("default")){
new Plan(name: "default",brandPartner: null,secRole: null).save(failOnError: true, flush: true)
log.info("initPlans: No default plan found, hence created a new default plan!")
}

那么我应该如何设置计划属性(用户定义类型)的默认值?

最佳答案

使用拦截器代替约束:

class User{
Plan plan
static beforeInsert = {
if( !plan ) Plan.withTransaction {
plan = Plan.findByName 'default'
}
}
}

关于grails - Grails用户定义类型的域类属性的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com