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

JPA Controladores de Entidades Relacionadas

Estas en el tema de JPA Controladores de Entidades Relacionadas en el foro de Java en Foros del Web. Buenas tengo el siguiente problema cuando intento borrar un registro de la bd. la base de datos se compone de dos tablas Departamentos Empleados estan ...
  #1 (permalink)  
Antiguo 06/02/2013, 13:26
 
Fecha de Ingreso: octubre-2007
Mensajes: 57
Antigüedad: 16 años, 7 meses
Puntos: 0
Pregunta JPA Controladores de Entidades Relacionadas

Buenas tengo el siguiente problema cuando intento borrar un registro de la bd.

la base de datos se compone de dos tablas

Departamentos
Empleados

estan relacionadas 1:N con un restricción en la clave foranea en cascada para actualizaciones y borrados...si borro un departamento se borran los registros empleados que pertenecen a ese departamento..

aqui el script SQL

Código PHP:
DROP SCHEMA IF EXISTS `empresabd` ;
CREATE SCHEMA IF NOT EXISTS `empresabd` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `
empresabd` ;

-- -----------------------------------------------------
-- 
Table `empresabd`.`departamentos`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `empresabd`.`departamentos` ;

CREATE  TABLE IF NOT EXISTS `empresabd`.`departamentos` (
  `
iddepINT NOT NULL AUTO_INCREMENT ,
  `
categoriaVARCHAR(45NOT NULL ,
  `
descripcionVARCHAR(200NOT NULL ,
  
PRIMARY KEY (`iddep`) )
ENGINE InnoDB;


-- -----------------------------------------------------
-- 
Table `empresabd`.`empleados`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `empresabd`.`empleados` ;

CREATE  TABLE IF NOT EXISTS `empresabd`.`empleados` (
  `
dniVARCHAR(10NOT NULL ,
  `
nombreVARCHAR(40NOT NULL ,
  `
apellidosVARCHAR(150NOT NULL ,
  `
direccionVARCHAR(200NOT NULL ,
  `
telVARCHAR(10NOT NULL ,
  `
iddepINT NOT NULL ,
  
PRIMARY KEY (`dni`) ,
  
INDEX `fk_empleados_departamentos` (`iddepASC) ,
  
CONSTRAINT `fk_empleados_departamentos`
    
FOREIGN KEY (`iddep` )
    
REFERENCES `empresabd`.`departamentos` (`iddep` )
    
ON DELETE CASCADE
    ON UPDATE CASCADE
)
ENGINE InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

CREATE USER 'userempresabd'@'localhost' IDENTIFIED BY '123';
GRANT SELECT 
INSERT ,
UPDATE ,
DELETE ON `empresabd` . * TO 'userempresabd'@'localhost';

INSERT INTO departamentos (categoriadescripcionVALUES 
('1a''RECURSOS HUMANOS'),
(
'1b''ID+D');

INSERT INTO empleados (dninombreapellidosdireccionteliddepVALUES
('11111111D''Pablo''Arjona''Calle 2''000111222''1'),
(
'22222222D''Ana''Arjone''Calle 3''000222333''2'); 
en netbeans genero las clases entidad a partir de la base de datos:

Clase entidad Departamentos

Código PHP:
package Entidades;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

@
Entity
@Table(name "departamentos")
@
XmlRootElement
@NamedQueries({
    @
NamedQuery(name "Departamentos.findAll"query "SELECT d FROM Departamentos d"),
    @
NamedQuery(name "Departamentos.findByIddep"query "SELECT d FROM Departamentos d WHERE d.iddep = :iddep"),
    @
NamedQuery(name "Departamentos.findByCategoria"query "SELECT d FROM Departamentos d WHERE d.categoria = :categoria"),
    @
NamedQuery(name "Departamentos.findByDescripcion"query "SELECT d FROM Departamentos d WHERE d.descripcion = :descripcion")})
public class 
Departamentos implements Serializable {
    private static final 
long serialVersionUID 1L;
    @
Id
    
@GeneratedValue(strategy GenerationType.IDENTITY)
    @
Basic(optional false)
    @
Column(name "iddep")
    private 
Integer iddep;
    @
Basic(optional false)
    @
Column(name "categoria")
    private 
String categoria;
    @
Basic(optional false)
    @
Column(name "descripcion")
    private 
String descripcion;
    @
OneToMany(cascade CascadeType.ALLmappedBy "iddep")
    private 
Collection<EmpleadosempleadosCollection;

    public 
Departamentos() {
    }

    public 
Departamentos(Integer iddep) {
        
this.iddep iddep;
    }

    public 
Departamentos(Integer iddepString categoriaString descripcion) {
        
this.iddep iddep;
        
this.categoria categoria;
        
this.descripcion descripcion;
    }

    public 
Integer getIddep() {
        return 
iddep;
    }

    public 
void setIddep(Integer iddep) {
        
this.iddep iddep;
    }

    public 
String getCategoria() {
        return 
categoria;
    }

    public 
void setCategoria(String categoria) {
        
this.categoria categoria;
    }

    public 
String getDescripcion() {
        return 
descripcion;
    }

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

    @
XmlTransient
    
public Collection<EmpleadosgetEmpleadosCollection() {
        return 
empleadosCollection;
    }

    public 
void setEmpleadosCollection(Collection<EmpleadosempleadosCollection) {
        
this.empleadosCollection empleadosCollection;
    }

    @
Override
    
public int hashCode() {
        
int hash 0;
        
hash += (iddep != null iddep.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 Departamentos)) {
            return 
false;
        }
        
Departamentos other = (Departamentosobject;
        if ((
this.iddep == null && other.iddep != null) || (this.iddep != null && !this.iddep.equals(other.iddep))) {
            return 
false;
        }
        return 
true;
    }

    @
Override
    
public String toString() {
        return 
"Entidades.Departamentos[ iddep=" iddep " ]";
    }
    

Clase entidad Empleados

Código PHP:
package Entidades;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@
Entity
@Table(name "empleados")
@
XmlRootElement
@NamedQueries({
    @
NamedQuery(name "Empleados.findAll"query "SELECT e FROM Empleados e"),
    @
NamedQuery(name "Empleados.findByDni"query "SELECT e FROM Empleados e WHERE e.dni = :dni"),
    @
NamedQuery(name "Empleados.findByNombre"query "SELECT e FROM Empleados e WHERE e.nombre = :nombre"),
    @
NamedQuery(name "Empleados.findByApellidos"query "SELECT e FROM Empleados e WHERE e.apellidos = :apellidos"),
    @
NamedQuery(name "Empleados.findByDireccion"query "SELECT e FROM Empleados e WHERE e.direccion = :direccion"),
    @
NamedQuery(name "Empleados.findByTel"query "SELECT e FROM Empleados e WHERE e.tel = :tel")})
public class 
Empleados implements Serializable {
    private static final 
long serialVersionUID 1L;
    @
Id
    
@Basic(optional false)
    @
Column(name "dni")
    private 
String dni;
    @
Basic(optional false)
    @
Column(name "nombre")
    private 
String nombre;
    @
Basic(optional false)
    @
Column(name "apellidos")
    private 
String apellidos;
    @
Basic(optional false)
    @
Column(name "direccion")
    private 
String direccion;
    @
Basic(optional false)
    @
Column(name "tel")
    private 
String tel;
    @
JoinColumn(name "iddep"referencedColumnName "iddep")
    @
ManyToOne(optional false)
    private 
Departamentos iddep;

    public 
Empleados() {
    }

    public 
Empleados(String dni) {
        
this.dni dni;
    }

    public 
Empleados(String dniString nombreString apellidosString direccionString tel) {
        
this.dni dni;
        
this.nombre nombre;
        
this.apellidos apellidos;
        
this.direccion direccion;
        
this.tel tel;
    }

    public 
String getDni() {
        return 
dni;
    }

    public 
void setDni(String dni) {
        
this.dni dni;
    }

    public 
String getNombre() {
        return 
nombre;
    }

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

    public 
String getApellidos() {
        return 
apellidos;
    }

    public 
void setApellidos(String apellidos) {
        
this.apellidos apellidos;
    }

    public 
String getDireccion() {
        return 
direccion;
    }

    public 
void setDireccion(String direccion) {
        
this.direccion direccion;
    }

    public 
String getTel() {
        return 
tel;
    }

    public 
void setTel(String tel) {
        
this.tel tel;
    }

    public 
Departamentos getIddep() {
        return 
iddep;
    }

    public 
void setIddep(Departamentos iddep) {
        
this.iddep iddep;
    }

    @
Override
    
public int hashCode() {
        
int hash 0;
        
hash += (dni != null dni.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 Empleados)) {
            return 
false;
        }
        
Empleados other = (Empleadosobject;
        if ((
this.dni == null && other.dni != null) || (this.dni != null && !this.dni.equals(other.dni))) {
            return 
false;
        }
        return 
true;
    }

    @
Override
    
public String toString() {
        return 
"Entidades.Empleados[ dni=" dni " ]";
    }
    

....sigue en siguiente post
  #2 (permalink)  
Antiguo 06/02/2013, 13:27
 
Fecha de Ingreso: octubre-2007
Mensajes: 57
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: JPA Controladores de Entidades Relacionadas

También genero las clases controller de las clases entidad con netbeans.. que lo hace al vuelo

Clase DepartamentosJpaController

Código PHP:
package Controladores;

import Controladores.exceptions.IllegalOrphanException;
import Controladores.exceptions.NonexistentEntityException;
import Entidades.Departamentos;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entidades.Empleados;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;


public class 
DepartamentosJpaController implements Serializable {

    public 
DepartamentosJpaController(EntityManagerFactory emf) {
        
this.emf emf;
    }
    private 
EntityManagerFactory emf null;

    public 
EntityManager getEntityManager() {
        return 
emf.createEntityManager();
    }

    public 
void create(Departamentos departamentos) {
        if (
departamentos.getEmpleadosCollection() == null) {
            
departamentos.setEmpleadosCollection(new ArrayList<Empleados>());
        }
        
EntityManager em null;
        try {
            
em getEntityManager();
            
em.getTransaction().begin();
            
Collection<EmpleadosattachedEmpleadosCollection = new ArrayList<Empleados>();
            for (
Empleados empleadosCollectionEmpleadosToAttach departamentos.getEmpleadosCollection()) {
                
empleadosCollectionEmpleadosToAttach em.getReference(empleadosCollectionEmpleadosToAttach.getClass(), empleadosCollectionEmpleadosToAttach.getDni());
                
attachedEmpleadosCollection.add(empleadosCollectionEmpleadosToAttach);
            }
            
departamentos.setEmpleadosCollection(attachedEmpleadosCollection);
            
em.persist(departamentos);
            for (
Empleados empleadosCollectionEmpleados departamentos.getEmpleadosCollection()) {
                
Departamentos oldIddepOfEmpleadosCollectionEmpleados empleadosCollectionEmpleados.getIddep();
                
empleadosCollectionEmpleados.setIddep(departamentos);
                
empleadosCollectionEmpleados em.merge(empleadosCollectionEmpleados);
                if (
oldIddepOfEmpleadosCollectionEmpleados != null) {
                    
oldIddepOfEmpleadosCollectionEmpleados.getEmpleadosCollection().remove(empleadosCollectionEmpleados);
                    
oldIddepOfEmpleadosCollectionEmpleados em.merge(oldIddepOfEmpleadosCollectionEmpleados);
                }
            }
            
em.getTransaction().commit();
        } 
finally {
            if (
em != null) {
                
em.close();
            }
        }
    }

    public 
void edit(Departamentos departamentosthrows IllegalOrphanExceptionNonexistentEntityExceptionException {
        
EntityManager em null;
        try {
            
em getEntityManager();
            
em.getTransaction().begin();
            
Departamentos persistentDepartamentos em.find(Departamentos.class, departamentos.getIddep());
            
Collection<EmpleadosempleadosCollectionOld persistentDepartamentos.getEmpleadosCollection();
            
Collection<EmpleadosempleadosCollectionNew departamentos.getEmpleadosCollection();
            List<
StringillegalOrphanMessages null;
            for (
Empleados empleadosCollectionOldEmpleados empleadosCollectionOld) {
                if (!
empleadosCollectionNew.contains(empleadosCollectionOldEmpleados)) {
                    if (
illegalOrphanMessages == null) {
                        
illegalOrphanMessages = new ArrayList<String>();
                    }
                    
illegalOrphanMessages.add("You must retain Empleados " empleadosCollectionOldEmpleados " since its iddep field is not nullable.");
                }
            }
            if (
illegalOrphanMessages != null) {
                throw new 
IllegalOrphanException(illegalOrphanMessages);
            }
            
Collection<EmpleadosattachedEmpleadosCollectionNew = new ArrayList<Empleados>();
            for (
Empleados empleadosCollectionNewEmpleadosToAttach empleadosCollectionNew) {
                
empleadosCollectionNewEmpleadosToAttach em.getReference(empleadosCollectionNewEmpleadosToAttach.getClass(), empleadosCollectionNewEmpleadosToAttach.getDni());
                
attachedEmpleadosCollectionNew.add(empleadosCollectionNewEmpleadosToAttach);
            }
            
empleadosCollectionNew attachedEmpleadosCollectionNew;
            
departamentos.setEmpleadosCollection(empleadosCollectionNew);
            
departamentos em.merge(departamentos);
            for (
Empleados empleadosCollectionNewEmpleados empleadosCollectionNew) {
                if (!
empleadosCollectionOld.contains(empleadosCollectionNewEmpleados)) {
                    
Departamentos oldIddepOfEmpleadosCollectionNewEmpleados empleadosCollectionNewEmpleados.getIddep();
                    
empleadosCollectionNewEmpleados.setIddep(departamentos);
                    
empleadosCollectionNewEmpleados em.merge(empleadosCollectionNewEmpleados);
                    if (
oldIddepOfEmpleadosCollectionNewEmpleados != null && !oldIddepOfEmpleadosCollectionNewEmpleados.equals(departamentos)) {
                        
oldIddepOfEmpleadosCollectionNewEmpleados.getEmpleadosCollection().remove(empleadosCollectionNewEmpleados);
                        
oldIddepOfEmpleadosCollectionNewEmpleados em.merge(oldIddepOfEmpleadosCollectionNewEmpleados);
                    }
                }
            }
            
em.getTransaction().commit();
        } catch (
Exception ex) {
            
String msg ex.getLocalizedMessage();
            if (
msg == null || msg.length() == 0) {
                
Integer id departamentos.getIddep();
                if (
findDepartamentos(id) == null) {
                    throw new 
NonexistentEntityException("The departamentos with id " id " no longer exists.");
                }
            }
            throw 
ex;
        } 
finally {
            if (
em != null) {
                
em.close();
            }
        }
    }

    public 
void destroy(Integer idthrows IllegalOrphanExceptionNonexistentEntityException {
        
EntityManager em null;
        try {
            
em getEntityManager();
            
em.getTransaction().begin();
            
Departamentos departamentos;
            try {
                
departamentos em.getReference(Departamentos.class, id);
                
departamentos.getIddep();
            } catch (
EntityNotFoundException enfe) {
                throw new 
NonexistentEntityException("The departamentos with id " id " no longer exists."enfe);
            }
            List<
StringillegalOrphanMessages null;
            
Collection<EmpleadosempleadosCollectionOrphanCheck departamentos.getEmpleadosCollection();
            for (
Empleados empleadosCollectionOrphanCheckEmpleados empleadosCollectionOrphanCheck) {
                if (
illegalOrphanMessages == null) {
                    
illegalOrphanMessages = new ArrayList<String>();
                }
                
illegalOrphanMessages.add("This Departamentos (" departamentos ") cannot be destroyed since the Empleados " empleadosCollectionOrphanCheckEmpleados " in its empleadosCollection field has a non-nullable iddep field.");
            }
            if (
illegalOrphanMessages != null) {
                throw new 
IllegalOrphanException(illegalOrphanMessages);
            }
            
em.remove(departamentos);
            
em.getTransaction().commit();
        } 
finally {
            if (
em != null) {
                
em.close();
            }
        }
    }

    public List<
DepartamentosfindDepartamentosEntities() {
        return 
findDepartamentosEntities(true, -1, -1);
    }

    public List<
DepartamentosfindDepartamentosEntities(int maxResultsint firstResult) {
        return 
findDepartamentosEntities(falsemaxResultsfirstResult);
    }

    private List<
DepartamentosfindDepartamentosEntities(boolean allint maxResultsint firstResult) {
        
EntityManager em getEntityManager();
        try {
            
CriteriaQuery cq em.getCriteriaBuilder().createQuery();
            
cq.select(cq.from(Departamentos.class));
            
Query q em.createQuery(cq);
            if (!
all) {
                
q.setMaxResults(maxResults);
                
q.setFirstResult(firstResult);
            }
            return 
q.getResultList();
        } 
finally {
            
em.close();
        }
    }

    public 
Departamentos findDepartamentos(Integer id) {
        
EntityManager em getEntityManager();
        try {
            return 
em.find(Departamentos.class, id);
        } 
finally {
            
em.close();
        }
    }

    public 
int getDepartamentosCount() {
        
EntityManager em getEntityManager();
        try {
            
CriteriaQuery cq em.getCriteriaBuilder().createQuery();
            
Root<Departamentosrt cq.from(Departamentos.class);
            
cq.select(em.getCriteriaBuilder().count(rt));
            
Query q em.createQuery(cq);
            return ((
Longq.getSingleResult()).intValue();
        } 
finally {
            
em.close();
        }
    }
    

  #3 (permalink)  
Antiguo 06/02/2013, 13:28
 
Fecha de Ingreso: octubre-2007
Mensajes: 57
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: JPA Controladores de Entidades Relacionadas

Clase EmpleadosJpaController

Código PHP:
package Controladores;

import Controladores.exceptions.NonexistentEntityException;
import Controladores.exceptions.PreexistingEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entidades.Departamentos;
import Entidades.Empleados;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class 
EmpleadosJpaController implements Serializable {

    public 
EmpleadosJpaController(EntityManagerFactory emf) {
        
this.emf emf;
    }
    private 
EntityManagerFactory emf null;

    public 
EntityManager getEntityManager() {
        return 
emf.createEntityManager();
    }

    public 
void create(Empleados empleadosthrows PreexistingEntityExceptionException {
        
EntityManager em null;
        try {
            
em getEntityManager();
            
em.getTransaction().begin();
            
Departamentos iddep empleados.getIddep();
            if (
iddep != null) {
                
iddep em.getReference(iddep.getClass(), iddep.getIddep());
                
empleados.setIddep(iddep);
            }
            
em.persist(empleados);
            if (
iddep != null) {
                
iddep.getEmpleadosCollection().add(empleados);
                
iddep em.merge(iddep);
            }
            
em.getTransaction().commit();
        } catch (
Exception ex) {
            if (
findEmpleados(empleados.getDni()) != null) {
                throw new 
PreexistingEntityException("Empleados " empleados " already exists."ex);
            }
            throw 
ex;
        } 
finally {
            if (
em != null) {
                
em.close();
            }
        }
    }

    public 
void edit(Empleados empleadosthrows NonexistentEntityExceptionException {
        
EntityManager em null;
        try {
            
em getEntityManager();
            
em.getTransaction().begin();
            
Empleados persistentEmpleados em.find(Empleados.class, empleados.getDni());
            
Departamentos iddepOld persistentEmpleados.getIddep();
            
Departamentos iddepNew empleados.getIddep();
            if (
iddepNew != null) {
                
iddepNew em.getReference(iddepNew.getClass(), iddepNew.getIddep());
                
empleados.setIddep(iddepNew);
            }
            
empleados em.merge(empleados);
            if (
iddepOld != null && !iddepOld.equals(iddepNew)) {
                
iddepOld.getEmpleadosCollection().remove(empleados);
                
iddepOld em.merge(iddepOld);
            }
            if (
iddepNew != null && !iddepNew.equals(iddepOld)) {
                
iddepNew.getEmpleadosCollection().add(empleados);
                
iddepNew em.merge(iddepNew);
            }
            
em.getTransaction().commit();
        } catch (
Exception ex) {
            
String msg ex.getLocalizedMessage();
            if (
msg == null || msg.length() == 0) {
                
String id empleados.getDni();
                if (
findEmpleados(id) == null) {
                    throw new 
NonexistentEntityException("The empleados with id " id " no longer exists.");
                }
            }
            throw 
ex;
        } 
finally {
            if (
em != null) {
                
em.close();
            }
        }
    }

    public 
void destroy(String idthrows NonexistentEntityException {
        
EntityManager em null;
        try {
            
em getEntityManager();
            
em.getTransaction().begin();
            
Empleados empleados;
            try {
                
empleados em.getReference(Empleados.class, id);
                
empleados.getDni();
            } catch (
EntityNotFoundException enfe) {
                throw new 
NonexistentEntityException("The empleados with id " id " no longer exists."enfe);
            }
            
Departamentos iddep empleados.getIddep();
            if (
iddep != null) {
                
iddep.getEmpleadosCollection().remove(empleados);
                
iddep em.merge(iddep);
            }
            
em.remove(empleados);
            
em.getTransaction().commit();
        } 
finally {
            if (
em != null) {
                
em.close();
            }
        }
    }

    public List<
EmpleadosfindEmpleadosEntities() {
        return 
findEmpleadosEntities(true, -1, -1);
    }

    public List<
EmpleadosfindEmpleadosEntities(int maxResultsint firstResult) {
        return 
findEmpleadosEntities(falsemaxResultsfirstResult);
    }

    private List<
EmpleadosfindEmpleadosEntities(boolean allint maxResultsint firstResult) {
        
EntityManager em getEntityManager();
        try {
            
CriteriaQuery cq em.getCriteriaBuilder().createQuery();
            
cq.select(cq.from(Empleados.class));
            
Query q em.createQuery(cq);
            if (!
all) {
                
q.setMaxResults(maxResults);
                
q.setFirstResult(firstResult);
            }
            return 
q.getResultList();
        } 
finally {
            
em.close();
        }
    }

    public 
Empleados findEmpleados(String id) {
        
EntityManager em getEntityManager();
        try {
            return 
em.find(Empleados.class, id);
        } 
finally {
            
em.close();
        }
    }

    public 
int getEmpleadosCount() {
        
EntityManager em getEntityManager();
        try {
            
CriteriaQuery cq em.getCriteriaBuilder().createQuery();
            
Root<Empleadosrt cq.from(Empleados.class);
            
cq.select(em.getCriteriaBuilder().count(rt));
            
Query q em.createQuery(cq);
            return ((
Longq.getSingleResult()).intValue();
        } 
finally {
            
em.close();
        }
    }
    


Hago una insercion y un update usando los metodos de las clases controladoras sin problema pero al probar hacer un borrado de un departamento no me deja si hay algun empleado en ese departamento.. me lanza un IllegalOrphanException

no se si tengo que modificar los metodos que me genera netbeans o no.

el codigo del main es el siguiente:

Código PHP:
package App;

import Controladores.*;
import Controladores.exceptions.IllegalOrphanException;
import Controladores.exceptions.NonexistentEntityException;
import Controladores.exceptions.PreexistingEntityException;
import Entidades.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class 
Main {

    public static 
void main(String args[]) {
        
//inicializamos el EntityManagerFactory
        
EntityManagerFactory emf Persistence.createEntityManagerFactory("empresaPU");

        
// instanciamos objetos de las clase controladora Departamentos
        
DepartamentosJpaController controlD = new DepartamentosJpaController(emf);
        
EmpleadosJpaController controlE = new EmpleadosJpaController(emf);
        try {                              
            
// utilizamos el metodo destroy para eliminar el departamento
            // al metodo solo le pasamos el id del departamento
            // Este método bucará por la propiedad id el registro 
            // en el base de datos para persistir los cambios
            
controlD.destroy(2);
        } catch (
IllegalOrphanException NonexistentEntityException ex) {
            
Logger.getLogger(Main.class.getName()).log(Level.SEVEREnullex);
        }

    }

me lanza esta excepción

Código PHP:
Controladores.exceptions.IllegalOrphanExceptionThis Departamentos (Entidades.Departamentosiddep=]) cannot be destroyed since the Empleados Entidades.Empleadosdni=22222222D in its empleadosCollection field has a non-nullable iddep field
no lo entiendo se supone que netbeans tendria que generar los metodos para que pudiese borrar un departamento y automaticamente cualquier empleado de ese departamento sin tener que modificarlo ....no entiendo esa IllegalOrphanException!!
  #4 (permalink)  
Antiguo 06/02/2013, 13:34
 
Fecha de Ingreso: octubre-2007
Mensajes: 57
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: JPA Controladores de Entidades Relacionadas

puedo solucionarlo modificando el metodo destroy

Código PHP:
public void destroy(Integer idthrows IllegalOrphanExceptionNonexistentEntityException {
        
EntityManager em null;
        try {
            
em getEntityManager();
            
em.getTransaction().begin();
            
Departamentos departamentos;
            try {
                
departamentos em.getReference(Departamentos.class, id);
                
departamentos.getIddep();
            } catch (
EntityNotFoundException enfe) {
                throw new 
NonexistentEntityException("The departamentos with id " id " no longer exists."enfe);
            }
            List<
StringillegalOrphanMessages null;
            
Collection<EmpleadosempleadosCollectionOrphanCheck departamentos.getEmpleadosCollection();
            for (
Empleados empleadosCollectionOrphanCheckEmpleados empleadosCollectionOrphanCheck) {
                
em.remove(empleadosCollectionOrphanCheckEmpleados);
//                if (illegalOrphanMessages == null) {
//                    illegalOrphanMessages = new ArrayList<String>();
//                }
//                illegalOrphanMessages.add("This Departamentos (" + departamentos + ") cannot be destroyed since the Empleados " + empleadosCollectionOrphanCheckEmpleados + " in its empleadosCollection field has a non-nullable iddep field.");
            
}
//            if (illegalOrphanMessages != null) {
//                throw new IllegalOrphanException(illegalOrphanMessages);
//            }
            
em.remove(departamentos);
            
em.getTransaction().commit();
        } 
finally {
            if (
em != null) {
                
em.close();
            }
        }
    } 
pero en dos tablas se hace rapido ...pero teniendo muuuchas tablas y muuchas relaciones de ese tipo la cosa se hace tediosa...no entiendo porque el método me lanza la excepción en vez de borrar el departamento y los empleados de este departamento..

se supone que la herramienta que tiene netbeans que genera las clases controller de las clases entidad agiliza la tarea y no la hace mas tediosa.

Etiquetas: netbeans
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 18:04.