Suppose the following:
class Group{
String name
static hasMany = [users:User]
}
class User{
String name
}
This means, you have lots of Users for some Group, but also a User might have other Groups, so can't use a "belongsTo". To delete a Group is really easy:
def b = Group.get(0)
b.delete(flush:true)
On the other hand, you might want to delete a User, but not the Group:
def b = User.get(0)
b.delete(flush:true)
This will throw a lot of exceptions from Hibernate and JDBC. How are you supposed to do it? Well, first of all, you'll need a way to get a Group for a given User, but since "users" is transitive, you can't do something like
Group.findByUser(user) so go ahead and add the following code to your Group class:
static Group findByUser(User user){
def criteria = Group.createCriteria()
def result = criteria.get {
users {
idEq(user.id)
}
}
return result
}
Now, go to your
UserController delete method and add the following
if (userInstance) {
try {
AlertGroup g = Group.findByUser(userInstance)
if(g){
g.users.remove(userInstance)
}
userInstance.delete(flush: true)
...
The clear call will empty the references in the current object so you don't get any trouble.
Hi, I have I have some groups and i have some contacts. contacts are in different groups. Now i want to delete a particular contact. I am able to delete a contact which exists in single group. But not able to delete the contact if it exists in multiple groups. Can u tell me how to do this.
ResponderEliminarThanks in advance.