3

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)

Armand
  • 23,463
  • 20
  • 90
  • 119

1 Answers1

7

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]
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Works a treat, thanks :=) The significant difference is changing jaq.friends< – Armand Mar 25 '10 at 19:51
  • Alison - the reason why they don't do the same thing is because << is invoking the leftShift method which simply adds it to the Set. "addToFriends" is a method added to the metaClass of Person that performs the correct underlying hibernate operations for persistence and relationship management. – th3morg Mar 20 '14 at 20:27