Grails GORM rarely works in domain classes
- by Vena
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.