2010-03-25 66 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

相關問題