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

I am having trouble getting a many-to-many relationship working in the grail. Is there something clearly 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 friends: ${bob.friends}"
        println "Jaq friends: ${jaq.friends}"
     }
} 

I would expect Bob to be friends with Jaq and vice versa, but when I start, I get the following output:

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

(I am using Grails 1.2.0)

+3
source share
1 answer

It works:

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

    String toString() {
        name
    }
}

and then in 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 friends: ${bob.friends}"
        println "Jaq friends: ${jaq.friends}"
     }
} 

I get the following:

Running Grails application..
Bob friends: [jaq]
Jaq friends: [bob]
+7
source

Source: https://habr.com/ru/post/1738517/


All Articles