I tried to override the dynamic method addTo* provided by Grails/GORM but it doesn't seem to work.
Here is the code :
class Match {
static hasMany = [players: Player, matchPlayers: MatchPlayer]
void addToPlayers(Player player) {
if (players.add(player)) {
MatchPlayer matchPlayer = new MatchPlayer(match: this, player: player)
matchPlayers.add(matchPlayer)
}
}
}
ma = new Match().save()
ma.addToPlayers(player1)
The issue is that when calling addToPlayers I got the following exception:
java.lang.NullPointerException: Cannot invoke method add() on null object
So basically it seems that I have to initialize myself the collection 'players'.
Well, before doing that, I would like to have some insights on GORM mechanism :
1 - What is the default implementation for collections in GORM (I know that it is an implementation of java.util.Set but which one?)
2 - Is it the right thing to do (by overriding the addToPlayers method) ? (My only need is to create/remove an object MatchPlayer each time a player is added/removed in the match instance). If yes, why do I have an exception? Do you have a better design for this?
Thank you.