在建立关系之后,仅保留Grails域*

时间:2016-01-11 18:14:48

标签: grails gorm gorm-mongodb

我想知道是否有可能创建一个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吗?

1 个答案:

答案 0 :(得分:2)

根据您建立关系的方式,这是完全可能的。它实际上与您实施的数据库无关。

家长班

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,默认为all class Foo { String name static hasMany = [bars: Bar] static mapping = { bars cascade: 'all' } } 。这也可以明确设置:

forEach
相关问题