xpusostomos
xpusostomos

Reputation: 1641

Using TRANSIENT grails GORM hibernate objects

What I'd like to do in my grails app is to create a lot of transient objects, and when the time is right... IF the time is right, then I would persist all the objects. In some cases, the time is never right, so they'd be thrown away and garbage collected.

But if I write some code like this:

    CollectingEvent collectingEvent = new CollectingEvent()
    CollectionUnit collectionUnit = new CollectionUnit()

    collectionUnit.collectingEvent = collectingEvent
    collectingEvent.collectionUnits.add(collectionUnit)

then I'll get a java.lang.NullPointerException because collectionUnits isn't initialized to a valid collection.

It's not clear if I should try and initialize it in the CollectingEvent object, or indeed what syntax I would use if I wanted to do that:

class CollectingEvent {
    static hasMany = [collectionUnits: CollectionUnit]
}

Is what I am trying to do something I ought to be doing in the GORM / hibernate library? Or am I going to have to store all my data somewhere else and only populate GORM objects when I'm sure I want it persisted?

Upvotes: 0

Views: 61

Answers (1)

Peter
Peter

Reputation: 5184

The transient problem has nothing to do with ne NullPointerException.

Please, try to explain in detail what you mean by transient and why the usual new CollectionEvent() and not saving this Object doen't work.

The NullPointer:

GORM uses Hibernate under the hood, but it puts an active record layer ontop of it.

Therefore, you should use the addTo* methods when you want to add a Domain Class to collection of another domain class. Like adding a CollectionUnit to a CollectionEvent.

You code should look like this:

    CollectingEvent collectingEvent = new CollectingEvent()
    CollectionUnit collectionUnit = new CollectionUnit()

    collectingEvent.addToCollectionUnits(collectionUnit)

Furthermore, your CollectionUnit class should declare that it belongs to the CollectionUnit. I guess, that the lifecycle of the CollectionUnit depends on the CollectionEvent, doesn't it?

 static belongsTo = [collectingEvent: CollectingEvent]

Upvotes: 0

Related Questions