【问题标题】:Maintaining both sides of self-referential many-to-many relationship in Grails domain object在 Grails 域对象中维护自引用多对多关系的双方
【发布时间】:2010-03-25 16:32:13
【问题描述】:

我在获取 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)

【问题讨论】:

    标签: grails groovy many-to-many grails-orm


    【解决方案1】:

    这似乎有效:

    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]
    

    【讨论】:

    • 工作愉快,谢谢 :=) 显着的区别是将 jaq.friends
    • Alison - 他们不做同样事情的原因是因为
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多