2010-03-25 37 views
3

我在使用grails时遇到了一些多对多关系的问题。有什么明显的错误有以下:在Grails域对象中维护双方的自引用多对多关系

class Person { 
    static hasMany = [friends: Person] 
    static mappedBy = [friends: 'friends'] 

    String name 
    List friends = [] 

    String toString() { 
     return this.name 
    } 
} 

class BootStrap { 
    def init = { servletContext -> 
     Person bob = new Person(name: 'bob').save() 
     Person jaq = new Person(name: 'jaq').save() 
     jaq.friends << bob 

     println "Bob's friends: ${bob.friends}" 
     println "Jaq's friends: ${jaq.friends}" 
    } 
} 

我预计鲍勃做朋友JAQ,反之亦然,但我得到以下输出在启动时:

Running Grails application.. 
Bob's friends: [] 
Jaq's friends: [Bob] 

(I”中号使用Grails 1.2.0)

回答

7

这似乎工作:

class Person { 
    static hasMany = [ friends: Person ] 
    static mappedBy = [ friends: 'friends' ] 
    String name 

    String toString() { 
     name 
    } 
} 

,然后在引导:

class BootStrap { 
    def init = { servletContext -> 
     Person bob = new Person(name: 'bob').save() 
     Person jaq = new Person(name: 'jaq').save() 

     jaq.addToFriends(bob) 

     println "Bob's friends: ${bob.friends}" 
     println "Jaq's friends: ${jaq.friends}" 
    } 
} 

我得到如下:

Running Grails application.. 
Bob's friends: [jaq] 
Jaq's friends: [bob] 
+0

工程请客,感谢:=)的显著差异正在改变jaq.friends <<鲍勃jaq.addToFriends(BOB)。我有些惊讶,他们不做同样的事情;只有在关系的一方禁止添加朋友才会很好。 – Armand 2010-03-25 19:51:28

+0

Alison - 他们不这样做的原因是因为<<正在调用leftShift方法,它只是将它添加到Set中。 “addToFriends”是一种添加到Person的metaClass的方法,用于为持久性和关系管理执行正确的底层hibernate操作。 – th3morg 2014-03-20 20:27:45