Reputation: 2516
I am using spring security and have the following entities: User, Role and UserRole which if I'm not mistaking are default. Besides I have extra entity which is called Employee and it owns a list of Users:
class Employee {
static hasMany = [users: User]
users cascade: "all"
...
}
UserRole looks like:
class UserRole implements Serializable {
User user
Role role
...
}
and this entity is represented by many to many table. When I delete Employee I want to delete all Users that are associated with Employee too. So for this purpose I've added cascade: "all". But I cannot delete User and don't delete Roles associated with him since I have many to many table. Right now I have a special code that does it. Maybe its somehow possible to do it with cascade in UserRole entity but for me it's no clear how because UserRole has pretty strange structure (but its defula one). Can someone help me with this please? Thank you.
Upvotes: 0
Views: 257
Reputation: 187499
If you want deletion of an employee to cascade to the users associated with the employee, you can achieve this by making the mapping bidrectional and making employee the owner, e.g.
class Employee {
static hasMany = [users: User]
}
class User {
static belongsTo = [employee: Employee]
}
If you can't define the relationship between User
and UserRole
similarly, then add the following to the User
class to ensure that associated UserRole
instances are deleted along with the User
instance that owns them:
def beforeDelete() {
User.withNewSession {
UserRole.findAllByUser(this)*.delete()
}
}
Upvotes: 2