在Grails域对象中维护自引用多对多关系的双方

时间:2010-03-25 16:32:13

标签: grails groovy many-to-many gorm

我遇到了一些在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}"
     }
} 

我希望Bob成为Jaq的朋友,反之亦然,但我在启动时得到以下输出:

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

(我正在使用Grails 1.2.0)

1 个答案:

答案 0 :(得分:7)

这似乎有效:

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

    String toString() {
        name
    }
}

然后在BootStrap中:

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]