Foros del Web » Programación para mayores de 30 ;) » Java »

Hibernate gabrar many to many

Estas en el tema de Hibernate gabrar many to many en el foro de Java en Foros del Web. Tengo un problema con la relacion many to many Si bien me guarda la relacion antes de guardar va hacia la base y hacer sobre ...
  #1 (permalink)  
Antiguo 24/09/2009, 12:44
 
Fecha de Ingreso: septiembre-2009
Mensajes: 1
Antigüedad: 14 años, 7 meses
Puntos: 0
Hibernate gabrar many to many

Tengo un problema con la relacion many to many

Si bien me guarda la relacion
antes de guardar va hacia la base y hacer sobre la tabla region pero recorriendo sobre region, y eso es lo que no intiendo. no deberia hacer por la pk completa?
Hibernate: insert into MessageMIT (functionalGroup, priority, service, netElemen
t, product, symptom, place, cause, messageId) values (?, ?, ?, ?, ?, ?, ?, ?, ?)

Hibernate:
Código problema:
Ver original
  1. select messages0_.region as region0_, messages0_.message as message0_
  2.  from MessagesRegions messages0_ where messages0_.region=?
Hibernate: update Message set eventId=?, speech=?, [date]=?, start=?, finish=?,
estimatedTime=?, [user]=?, messageStatus=?, messageScope=?, category=?, channels
=?, incidence=?, incidenceOther=? where id=?
Hibernate: insert into MessagesRegions (region, message) values (?, ?)


tengo el siguiente codigo

Código:
/**
     *  hibernate.set
     *      table="MessagesRegions"
     *      inverse="true"
     *      cascade="save-update"
     *  hibernate.collection-key
     *      column="message"
     *      unique="true"
     *      not-null="true"
     *      
     *  hibernate.collection-many-to-many
     *      column="region"
     *      class="ar.com.tma.eb.olm.server.entity.message.MessageRegion"
     *      readonly="true"
     *	hibernate.collection-cache
     *		usage="nonstrict-read-write" 
	 */
	public Set getRegions() {
		return regions;
	}
	public void setRegions(Set value) {
		regions = value;
	}
	public void addRegion(MessageRegion region) {
		if (region==null) {
			throw new IllegalArgumentException("null MessageRegion");
		}
		 
		region.getMessages().add(this);
		getRegions().add(region);
	}
Código:
public MessageRegion() {
	}
	
    /**
     *  hibernate.set
     *      table="MessagesRegions"
     *      lazy="true"
     *      readonly="true"
     *  hibernate.collection-key
     *      column="region"
     *  hibernate.collection-many-to-many
     *      column="message"
     *      class="ar.com.tma.eb.olm.server.entity.message.MessageMIT"
     */
    public Set getMessages() {
        return messages;
    }
    public void setMessages(Set value) {
        messages = value;
    }
Código:
	Session session = HFactory.currentSession();
			
			MessageMIT message = new MessageMIT();
			message.setDate(new Date());
			message.setUser(user);
			message.setCategory(category);
			message.setFunctionalGroup(functionalGroup);
			message.setMessageStatus(status);
			message.setChannelsAsSet(channels);
			message.setPriority(priority);
			message.setNetElement(netElement);
			message.setProduct(product);
			message.setService(service);
			message.setSymptom(symptom);
			message.setPlace(place);
			message.setStart(start);
			message.setFinish(finish);
			message.setEstimatedTime(estimatedTime);
			message.setCause(cause);			
			message.setIncidence(incidence);
			message.setSpeech(speech);
			message.setIncidenceOther(incidenceOther);
			message.setMessageScope(scopes);
			
			// create message
			session.save(message);
			session.flush();
			
			logger.debug("created message "+message.getId());
			// add regions
			for (Iterator it = regions.iterator(); it.hasNext();) {
				MessageRegion region = (MessageRegion) it.next();
				logger.debug("adding MessageRegion "+region.getId()+" to Message "+message.getId());
				message.addRegion(region);
			}
			// add voice nets
			for (Iterator it = voiceNets.iterator(); it.hasNext();) {
				MessageVoiceNet voiceNet = (MessageVoiceNet) it.next();
				logger.debug("adding MessageVoiceNet "+voiceNet.getId()+" to Message "+message.getId());
				message.addVoiceNet(voiceNet);
			}
			// add data nets
			for (Iterator it = dataNets.iterator(); it.hasNext();) {
				MessageDataNet dataNet = (MessageDataNet) it.next();
				logger.debug("adding MessageDataNet "+dataNet.getId()+" to Message "+message.getId());
				message.addDataNet(dataNet);
			}
			// add incidences
			for (Iterator it = incidences.iterator(); it.hasNext();) {
				MessageIncidence messageIncidence = (MessageIncidence) it.next();
				logger.debug("adding MessageIncidence "+messageIncidence.getId()+" to Message "+message.getId());
				message.addIncidence(messageIncidence);
			}

			// setup eventId
			if (eventId==null) {
				message.setEventId(message.getId());
			}
			else {
				message.setEventId(eventId);
			}
			// update message
			session.update(message);
			session.flush();
			
			
			logger.debug("created/updated message MIT id:"+message.getId()+" eventId:"+message.getEventId());
			displayEventCreation(message);
			return (MessageMIT) message;
		} catch (HibernateException e) {
			logger.error("error creating event MIT");
			e.printStackTrace();
			
			throw new MessageException();
		}
Muchas gracias por alguna ayuda
  #2 (permalink)  
Antiguo 14/11/2012, 21:25
 
Fecha de Ingreso: noviembre-2012
Ubicación: Argentina
Mensajes: 5
Antigüedad: 11 años, 5 meses
Puntos: 0
Respuesta: Hibernate gabrar many to many

Buenas Tardes, estoy teniendo un problema bastante especifico.
Les comento a ver si alguien me puede ayudar con esto.

Tengo 3 tablas: Tabla Cliente, Tabla direccion y una tabla de referencia "client_address" que solo tiene 2 campos (IDCliente y IDDireccion)
(la relacion es many to many)

EN uno de los HBM, las mismas estan configuradas asi:
<set name="addresses" table="client_address" lazy="true" cascade="all-delete-orphan" inverse="true" >
<key column="id_client"/>
<many-to-many class="com.asofarma.fm.fe.model.Direccion" column="id_address"/>
</set>

ESTE CODIGO XML LO QUE HACE ES AL HACER UN SAVE DEL OBJETO ES CREAR:
• 1 registro en client_address(tabla intermedia)
• 1 registro en Address(en la tabla maestrs)

Aquí me surge el problema de que a veces en la pantalla necesito realizar una creacion de tabla maestra + tabla de referencia(asociacion) y a veces no, ya que los datos en la maestra ya existian, y solamente tengo que hacer la asociacion(insert en la tabla de referencia)

Tal cual como esta el XML, hibernete me esta insertando 2 registros en los 2 casos:
1 registro en la tabla maestra
1 registro en la tabla de referencia (asociacion el registro creado recientemente)

CASOS:
Tengo casos en los que le CREO "UN DOMICILIO" a un cliente.Al ser un nuevo domicilio estaria bien que se cree un nuevo registro en domicilio y luego otro nuevo registro en la tabla de referencia asociando el domicilio con el cliente.
Tengo otro caso que EL DOMICILIO ya existe, y solamente se lo selecciono al cliente, por lo tanto en la tabla domicilio este ya existe, debiendo solamente registrar la asociacion en la tabla de referencia. (ESTE ULTIMO ES EL QUE NO PUEDO SOLUCIONAR)

Por favor, agradezco alguna orientacion y/o comentarios.

Gracias
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 11:00.