Graals vede il mio oggetto appena istanziato come null in bootstrap.groovy
-
29-10-2019 - |
Domanda
Ho 2 classi e un enum. Una classe è un involucro per l'ENUM che contiene sia l'Enum che la sua rappresentazione di stringa, l'altra è una classe utente. L'ENUM definisce il tipo di utente. Sono impostati come segue:
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')
}
}
Il mio enum è il seguente:
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
}
}
e la mia classe di avvolgimento come segue:
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)")
}
}
Tutte cose piuttosto standard. Ora voglio bootstrap un utente nel DB:
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)
Quando colpisce la linea AddTORoles, si rompe e mi dà il messaggio di errore:
No signature of method: za.co.hollard.User.addToRoles() is applicable for argument types: (za.co.hollard.UserRole) values: [za.co.hollard.UserRole : null]
Ma se lancio alcune println prima del metodo AddTORoles - posso sondare l'oggetto UserRole appena creato ed estrarre esattamente i valori con cui è stato creato?
Soluzione
Credo che non puoi usare "aggiungi*" unles che hai definito l'associazione come una mappatura da uno a molti tramite "Hasmany". In classe 'utente' sostituire,
List<UserRole> roles
insieme a
static hasMany = [ roles:UserRole]