Search code examples
grailsgrails-ormgorm-mongodb

Persist Grails Domains *ONLY* after Relationship built


I'm wondering if its possible to create a grails domain object, but only have it persist on command as opposed as when we do operations on it.

To be more precise, this is what I have to do now:

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

What I want:

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? 

My impressions is that the latter would be far faster if there are many relationships to associate. Am I really just wanting NoSQL here?


Solution

  • Depending on how you have your relationships set up, this is entirely possible. It really has nothing to do with what database you have implemented.

    Parent class

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

    Child class

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

    Execution

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

    The key is the belongsTo which defaults to a cascade of all. This can be explicitly set as well:

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