Grails在BootStrap.groovy中将我刚刚实例化的对象视为null

时间:2012-02-22 10:59:45

标签: grails missingmethodexception

我有2个班级和一个Enum。一个类是Enum的包装器,它包含枚举和它的字符串表示,另一个是User类。枚举定义了用户的类型。它们的设置如下:

Class User {

    String username
    String password

    String firstName
    String lastName
    String emailAddress
    UserStatus status
    UserType type
    Date dateCreated

    List<UserRole> roles

    static mapping = {
        roles(fetch: 'join')
    }
}

My Enum如下:

enum RoleType {
    SUPER_USER('superuser','Super User'),
    SUPPORT_USER('supportuser','Support User'),
    STANDARD('standard','Standard')

    String id
    String name

    RoleType(String id, String name) {
        this.id = id
        this.name = name
    }

    String toString() {
        name
    }
}

和我的包装类如下:

class UserRole {

    static belongsTo = [user:User]

    static auditable = true

    RoleType roleType
    String role

    static constraints = {
        role(nullable:false, blank:false)
        roleType(nullable:false, inList:RoleType.values().toList())
    }

    static mapping = {
        sort(role: "asc")
        role(role: IdentityEnumType,sqlType: "varchar(40)")
    }
}

所有相当标准的东西。现在我想将用户引导到数据库中:

    User user = new User(
            username:'support@quirk.biz',
            password:'ilovequirk',
            status:UserStatus.ACTIVE,
            type:UserType.QUIRK,
            firstName:'Quirk',
            lastName:'Support',
            emailAddress:'support@quirk.biz'
        )

        UserRole userRole = new UserRole(roleType:RoleType.SUPER_USER, role:RoleType.SUPER_USER.toString())
        user.addToRoles(userRole)

        user.save(failOnError:true)

当它击中addToRoles行时,它会断开并给出错误消息:

No signature of method: za.co.hollard.User.addToRoles() is applicable for argument types: (za.co.hollard.UserRole) values: [za.co.hollard.UserRole : null]

但是如果我在addToRoles方法之前抛出一些printlns - 我可以探测新创建的UserRole对象并准确地获取它创建的值?

1 个答案:

答案 0 :(得分:1)

我相信你不能使用'add *',除非你通过'hasMany'将关联定义为一对多的映射。在“用户”替换中,

 List<UserRole> roles

 static hasMany = [ roles:UserRole]