我在使用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)
解决方法
这似乎有效:
- 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]