Showing posts with label discard. Show all posts
Showing posts with label discard. Show all posts

Tuesday, November 19, 2013

grails deleted object would be re-saved by cascade error

have the 'User' as set-up below. I am trying to delete a 'User' by user.delete(flush: true), and I get the following error:
org.hibernate.ObjectDeletedException: deleted object would be re-saved by 
cascade (remove deleted object from associations): [User#2]
 


class User {
    Integer id;
    String name;

    static belongsTo = [
            role: Role
    ]

    static constraints = {

    }
}


class Role {
    Integer id;

    static hasMany = [
            userList: User
    ]

    static constraints = {

    }
}

To make things short: Hibernate, and so Grails will want to save() the role object at the end of the Hibernate session (in your case at the .delete(flush:true) call) because it detects that the object has been modified (a user has been suppressed). And the role must have kept a link toward the user, causing Hibernate to feel you will delete() the user to save() it back again.
To workaround this:
 def role = user.role; 
 role.discard(); 
 user.delete(flush:true);
This tell Hibernate not to save() the role without you asking for it.