Grails GORM rarely works in domain classes

Posted by Vena on Stack Overflow See other posts from Stack Overflow or by Vena
Published on 2012-10-07T21:28:38Z Indexed on 2012/10/07 21:37 UTC
Read the original article Hit count: 227

Filed under:
|

I have many to many relationship between User and Organization. I want to delete user from all his organizations when the user is being deleted, so this is basically what I came up with:

class User {
    ...

    def beforeDelete() {
        def user = User.get(id)
        Organization.all.each {
            it.removeFromMembers(user)
            it.save()
        }
    }
}

This surprisingly doesn't work because User.get(id) returns null even though the user with the given id is in the database, when I look at the log, no sql statement is even executed. So I tried to use load() method insted. ObjectNotFoundException is the result then. So I tried this as I was quite desperate:

def user = User.find("from User as u where u.id = ?", [1L])

This, for some reason, works. But now, the line with it.removeFromMembers(user) throws NullPointerException.

I tried to put this logic in my UserController and it works!

Why is this? Why can't I do this in domain classes? This makes beforeDelete hook (and all the others too) pretty useless.

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about grails