Grails用户定义类型的域类属性的默认值
我有一个域类计划,类似于:Grails用户定义类型的域类属性的默认值,grails,gorm,Grails,Gorm,我有一个域类计划,类似于: class Plan{ String name static constraints={ name(unique:true,nullable:false) } } 另一个域类是用户: class User{ // Other attribures and code // .... Plan plan static constraints = { // other constraints.. plan(nullable:fals
class Plan{
String name
static constraints={
name(unique:true,nullable:false)
}
}
另一个域类是用户:
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'
}
}
}
如果以后添加“计划”属性,这会为已经存在的用户类对象指定null或默认值吗?对于已经存在的用户,您必须在更新之前使用相同的代码添加
拦截器