0

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

4

1 回答 1

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默认为 a cascadeof 的all。这也可以显式设置:

class Foo {
    String name

    static hasMany = [bars: Bar]

    static mapping = {
        bars cascade: 'all'
    }
}
于 2016-01-12T01:02:21.237 回答