在Grails域对象中维护自引用多对多关系的双方 [英] Maintaining both sides of self-referential many-to-many relationship in Grails domain object

查看:109
本文介绍了在Grails域对象中维护自引用多对多关系的双方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用grails时遇到了一些多对多关系的问题。以下是有什么明显的错误:

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

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

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]

(我使用的是Grails 1.2.0)

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

然后在BootStrap中:

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]

这篇关于在Grails域对象中维护自引用多对多关系的双方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆