2012-02-22 66 views
0

我有2個類和一個Enum。一個類是包含Enum和它的字符串表示的Enum的包裝器,另一個類是一個User類。枚舉定義了用戶的類型。他們設置如下:Grails在BootStrap.groovy中將我的新實例化對象視爲null

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') 
    } 
} 

我枚舉如下:

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

都是標準的東西。現在我想引導用戶到DB:

User user = new User(
      username:'[email protected]', 
      password:'ilovequirk', 
      status:UserStatus.ACTIVE, 
      type:UserType.QUIRK, 
      firstName:'Quirk', 
      lastName:'Support', 
      emailAddress:'[email protected]' 
     ) 

     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] 

但是,如果我扔在一些printlns的addToRoles前方法 - 我可以探測新創建的UserRole對象,並確切地獲得它創建的值?

+0

這'null'意味着你'UserRole'具有空ID(因爲它沒有保存),從默認的'toString'履行 – 2012-02-22 11:07:41

回答

1

我相信你不能使用'addTo *'unles,你已經通過'hasMany'將該關聯定義爲一對多映射。在課堂上 '用戶' 代替,

List<UserRole> roles 

static hasMany = [ roles:UserRole]