【问题标题】:Persist Grails Domains *ONLY* after Relationship built建立关系后*仅*保留 Grails 域
【发布时间】:2016-04-16 03:51:06
【问题描述】:

我想知道是否可以创建一个 grails 域对象,但它只能在命令上持续存在,而不是在我们对其进行操作时。

更准确地说,这就是我现在要做的:

Foo foo = new Foo(name:"asdf")
Bar bar = new Bar(name:"gzxj")
bar.save() // persist here 
foo.save() // persist here
foo.addToBars(bar) //  now I have to build the relationship

我想要什么:

Foo foo = new Foo(name:"asdf")
Bar bar = new Bar(name:"gzxj")
foo.addToBars(bar) //  just build the relationship
bar.save() // would be great to ignore this step
foo.save() // can I now atomically build both objects and create the relationships? 

我的印象是,如果有很多关系要关联,后者会快得多。我真的只是想要 NoSQL 吗?

【问题讨论】:

    标签: grails grails-orm gorm-mongodb


    【解决方案1】:

    根据您建立关系的方式,这是完全可能的。这和你实现的数据库真的没有关系。

    父类

    class Foo {
        String name
    
        static hasMany = [bars: Bar]
    }
    

    儿童班

    class Bar { 
        String name
    
        Foo foo //optional back reference       
        static belongsTo = Foo
    }
    

    执行

    Foo foo = new Foo(name: 'a')
    Bar bar = new Bar(name: 'b')
    foo.addToBars(bar)
    foo.save()
    
    //or even more terse
    
    Foo foo = new Foo(name: 'c')
    foo.addToBars(new Bar(name: 'd'))
    foo.save()
    

    密钥是belongsTo,默认为allcascade。这也可以显式设置:

    class Foo {
        String name
    
        static hasMany = [bars: Bar]
    
        static mapping = {
            bars cascade: 'all'
        }
    }
    

    【讨论】:

    • 啊。 .是的,我可能没有建造 belongsTo 。我还需要一段时间才能对其进行测试,但这是有道理的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2014-02-22
    相关资源
    最近更新 更多