sábado, 6 de noviembre de 2010

Relación Uno Varios

Para este ejemplo vamos a utilizar mi post llamado Creacion de Unidad de Persistencia con MySQL en Netbeans.
En esta relación vamos a crear un paquete llamado com.ejemplo.entidades.unovarios



Creamos dentro una Entity Class llamada Producto,


que tendrá las variables miembro:
nombre de tipo String y detalle del tipo Detalle(Clase que ya vamos a crear) que tendra una anotación del tipo ManyToOne con Detalle, generamos sus respectivos getters y setters, junto con un costructor que recibe el id y el nombre. Con lo que la clase nos queda de la siguiente forma:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package com.ejemplo.entidades.unovarios;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

/**
*
* @author santiago
*/
@Entity
public class Producto implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nombre;
@ManyToOne
private Detalle detalle;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public Detalle getDetalle() {
return detalle;
}

public void setDetalle(Detalle detalle) {
this.detalle = detalle;
}

public String getNombre() {
return nombre;
}

public void setNombre(String nombre) {
this.nombre = nombre;
}

public Producto(){
}

public Producto(Long id, String nombre) {
this.id = id;
this.nombre = nombre;
}



@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Producto)) {
return false;
}
Producto other = (Producto) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "com.ejemplo.entidades.unovarios.Producto[id=" + id + "]";
}

}


Luego creamos otra Entity Class llamada Detalle que tendrá como variables miembro descripción del tipo String y una Lista de tipo Producto llamada productos que tiene una anotación OneToMany. Tambien generamos getters y setters. De tal manera que nos quede de la siguiente manera:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package com.ejemplo.entidades.unovarios;

import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

/**
*
* @author santiago
*/
@Entity
public class Detalle implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String descripcion;
@OneToMany(mappedBy="detalle",cascade=CascadeType.ALL)
private List productos;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getDescripcion() {
return descripcion;
}

public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}

public List getProductos() {
return productos;
}

public void setProductos(List productos) {
this.productos = productos;
}




@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Detalle)) {
return false;
}
Detalle other = (Detalle) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "com.ejemplo.entidades.unovarios.Detalle[id=" + id + "]";
}

}

Hecho este código, vamos a crear la clase Utilitario dentro de com.ejemplo.sesion. Ahí hacemos una inyección del persistence Context y usamos un EntityManager para usar la entidad antes creada. Además creamos una funcion llamada relacionUnoVarios, que se encargará de insertar datos (No olvidemos que esta funcion tiene que estar tambien en la interface remota, podriamos usar Insert Code > Add Business Method en Netbeans). Es decir:


package com.ejemplo.session;

import com.ejemplo.entidades.unovarios.Detalle;
import com.ejemplo.entidades.unovarios.Producto;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class Utilitario implements UtilitarioRemote {
@PersistenceContext EntityManager em;

public void relacionUnoVarios() {
Detalle detalle = new Detalle();
Producto producto1 = new Producto();
producto1.setId(6L);
producto1.setNombre("Cafe");
producto1.setDetalle(detalle);
Producto producto2 = new Producto();
producto2.setId(7L);
producto2.setNombre("Té");
producto2.setDetalle(detalle);
List productos = new ArrayList();
productos.add(producto1);
productos.add(producto2);
detalle.setId(10L);
detalle.setDescripcion("Esta es una prueba de detalles");
detalle.setProductos(productos);
em.persist(detalle);
}

}

El metodo Main tiene el siguiente código:

package relaciones;

import com.ejemplo.session.UtilitarioRemote;
import javax.ejb.EJB;

public class Main {

@EJB private static UtilitarioRemote utilitario;
public static void main(String[] args) {
utilitario.relacionUnoVarios();
}
}

y las consultas a las tablas tienen la siguiente información


No hay comentarios:

Publicar un comentario