pyb
pyb

Reputation: 5269

Grails / GORM : org.hibernate.AssertionFailure: null id in xyz (don't flush the Session after an exception occurs)

Edit: got a -1, could you please explain why? I searched for duplicates and did not find any.

Posting a Q/A for the issue I just encountered:

class Pineapple {
    def pineappleService

    Supplier supplier;

    def beforeInsert() {
        pineappleService.beforeInsert(this);
    }
}

class PineappleService {
    def beforeInsert(Pineapple pineapple) {
         Pineapple.withNewSession {
             // some logic
             pineapple.supplier.save();
         }
    }
}

Exception:

org.hibernate.AssertionFailure: null id in xyz (don't flush the Session after an exception occurs)

Upvotes: 2

Views: 1187

Answers (1)

pyb
pyb

Reputation: 5269

The trick is to move the closure to the domain class:

class Pineapple {
    def pineappleService

    Supplier supplier;

    def beforeInsert() {
        Pineapple.withNewSession {
            pineappleService.beforeInsert(this);
        }
    }
}

class PineappleService {
    def beforeInsert(Pineapple pineapple) {
         // some logic
         pineapple.supplier.save();
    }
}

Documentation:

Notice the usage of withNewSession method above. Since events are triggered whilst Hibernate is flushing using persistence methods like save() and delete() won't result in objects being saved unless you run your operations with a new Session.

Fortunately the withNewSession method lets you share the same transactional JDBC connection even though you're using a different underlying Session.

Upvotes: 3

Related Questions