如何覆盖addTo *和RemoveFrom * GORM / Grails方法? [英] How to override addTo* and RemoveFrom* GORM/Grails methods?

查看:65
本文介绍了如何覆盖addTo *和RemoveFrom * GORM / Grails方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图覆盖Grails / GORM提供的动态方法addTo *,但它似乎不起作用。



以下是代码:

  class Match {
static hasMany = [players:Player,matchPlayers:MatchPlayer]

void addToPlayers(玩家玩家){
if(players.add(player)){
MatchPlayer matchPlayer = new MatchPlayer(match:this,player:player)
matchPlayers.add(matchPlayer)
}

$ b $ ma = new Match()。save()
ma.addToPlayers(player1)

问题是,当调用addToPlayers时,我得到以下异常:

  java.lang.NullPointerException:无法在null对象上调用方法add()

所以基本上看来,我必须自己初始化集合'玩家'。



好吧,在这之前,我想对GORM机制有一些见解:



1 - GORM集合的默认实现是什么(我知道它是java.util.Set的实现,但是哪一个实现?)

2 - 是否正确(通过重写addToPlayers方法)? (我唯一需要的是每次在匹配实例中添加/删除玩家时创建/删除MatchPlayer对象)。如果是,为什么我有例外?你有更好的设计吗?



谢谢。

解决方案

您的代码与标准Grails方法类似,请参阅org.codehaus.groovy.grails.pluginsDomainClassGrailsPlugin.addRelationshipManagementMethods()中的代码。如果不指定集合的​​类型,则初始的Set实现是HashSet,如果指定SortedSet,则为TreeSet,例如

  static hasMany = [players:Player,matchPlayers:MatchPlayer] 
SortedSet players


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.

解决方案

Your code is similar to the standard Grails approach, see the code for this in org.codehaus.groovy.grails.pluginsDomainClassGrailsPlugin.addRelationshipManagementMethods(). The initial Set implementation is either a HashSet if you don't specify the type of the collection, or a TreeSet if specify a SortedSet, e.g.

static hasMany = [players: Player, matchPlayers: MatchPlayer]
SortedSet players

这篇关于如何覆盖addTo *和RemoveFrom * GORM / Grails方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆