开发者

Maintaining both sides of self-referential many-to-many relationship in Grails domain object

I'm having some problems getting a many-to-many relationship working in grails. Is there anything obviously wrong with the following:

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}"
     }
} 

I'd expect Bob to be friends with Jaq and vice-versa, but I get the following output at startup:

开发者_开发问答
Running Grails application..
Bob's friends: []
Jaq's friends: [Bob]

(I'm using Grails 1.2.0)


This seems to work:

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

    String toString() {
        name
    }
}

and then in the 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}"
     }
} 

I get the following:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜