Search code examples
hibernategrailsgrails-orm

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)


Solution

  • 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.