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

时间:2015-09-19 12:15:06

标签: grails gorm

我有一个域类计划,如:

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!")
}

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

1 个答案:

答案 0 :(得分:1)

使用拦截器而不是约束:

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