Noticias Weblogs Foros Wiki Código

Meta-Info

¿Que es?

Planeta Código es un agregador de weblogs sobre programación y desarrollo en castellano. Si eres lector te permite seguirlos de modo cómodo en esta misma página o mediante el fichero de subscripción.

rss subscripción

Sponsors

Puedes utilizar las siguientes imagenes para enlazar PlanetaCodigo:
planetacodigo

planetacodigo

Si tienes un weblog de programación y quieres ser añadido aquí, envíame un email solicitándolo.

Idea: Juanjo Navarro

Diseño: Albin

Monocaffe

Grails hasMany Delete

Febrero 16th, 2011 - [Enlace local]

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.

» Leer más, comentarios, etc...

Información legal y técnica