我有2个类(class)和一个枚举。一个类是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')
}
}
我的枚举如下:
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对象,并确切地得出它使用创建的值?
最佳答案
我相信您不能使用“addTo *”,除非您已通过“hasMany”将关联定义为一对多映射。在“用户”类别中,
List<UserRole> roles
与
static hasMany = [ roles:UserRole]
关于grails - Grails在BootStrap.groovy中看到我的新实例化对象为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9393505/