Search code examples
grailsgrails-orm

GORM - all-delete-orphan not working


I have 2 classes in mygrails project called Profile and Licence Here is the outline of the stuff that matters in the classes

class Profile {

    Set<Licence> licenceKeys

    static hasMany = [licenceKeys:Licence]

   static constraints = {
        licenceKeys nullable:true
    }
    static mapping = {
        licenceKeys cascade: 'all-delete-orphan'
    }
}

class Licence {

    Profile profile
    String licenceKey

    static belongsTo = [profile:Profile]

    static constraints = {
        profile nullable:false
        licenceKey blank:true, nullable:true, unique:true
    }   
}

When I run the following code in one of my controllers

    if (!profile.licenceKeys.clear()) {
        log.error ("Error occured removing licence keys from the database");
        userProfile.errors.each { err -> println err; }
    }  else {
        log.info("Successfully remove licence keys from the database");
    }

I get the following error message in the console and the licencekeys remain in the database org.springframework.validation.BeanPropertyBindingResult: 0 errors The keys are removed from the licenceKeys set in the Profile class but remain in the databse

I have 2 questions is it possible to get better debug output for the error message that I got Am I missing anything to ensure that the licekeys are removed from the database?

Thanks


Solution

  • The clear() method will not actually do the work of deleting form the database you'll want to save after the clear(). Try...

    profile.licenceKeys.clear();
    if (!profile.save(flash:true)) {
        log.error ("Error occured removing licence keys from the database");
        userProfile.errors.each { err -> println err; }
    }  else {
        log.info("Successfully remove licence keys from the database");
    }
    

    For your second question you'll want to get the errors from the domain object that failed saving like so....

     if (!profile.save(flash:true)) {
        log.error ("Error occured removing licence keys from the database");
        profile.errors.each { err -> println err; }
    }