2

Estoy trabajando un crud en java jpa y eclipselink, una tabla notas está relacionada con alumno, docente, curso. Cuando quiero insertar un nuevo registro de notas me manda el siguiente error:

Error no se guardo During synchronization a new object was found through a relationship that was not marked cascade PERSIST: SEGUNDO JESUS.

entidad notas: esta tiene todas sus relaciones y entidades ya generadas:

package com.sistema.colegio.Pojo;

import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;


@Entity
@Table(name="notas")
@NamedQuery(name="Nota.findAll", query="SELECT n FROM Nota n")
public class Nota implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.TABLE)
    private String codigo;

    @Temporal(TemporalType.DATE)
    private Date fecha;

    private byte[] foto;

    private double nota;

    private String tema;

    private String unidad;

    @ManyToOne
    @JoinColumn(name="ALUMNO", referencedColumnName = "IdAlumno")
    private Alumno alumnoBean;

    //bi-directional many-to-one association to Curso
    @ManyToOne
    @JoinColumn(name="CURSO", referencedColumnName = "IdCurso")
    private Curso cursoBean;

    //bi-directional many-to-one association to Docente
    @ManyToOne
    @JoinColumn(name="PROFESOR", referencedColumnName = "IdDocente")
    private Docente docente;

    public Nota() {
    }

    public String getCodigo() {
        return this.codigo;
    }

    public void setCodigo(String codigo) {
        this.codigo = codigo;
    }

    public Date getFecha() {
        return this.fecha;
    }

    public void setFecha(Date fecha) {
        this.fecha = fecha;
    }

    public byte[] getFoto() {
        return this.foto;
    }

    public void setFoto(byte[] foto) {
        this.foto = foto;
    }

    public double getNota() {
        return this.nota;
    }

    public void setNota(double nota) {
        this.nota = nota;
    }

    public String getTema() {
        return this.tema;
    }

    public void setTema(String tema) {
        this.tema = tema;
    }

    public String getUnidad() {
        return this.unidad;
    }

    public void setUnidad(String unidad) {
        this.unidad = unidad;
    }

    public Alumno getAlumnoBean() {
        return this.alumnoBean;
    }

    public void setAlumnoBean(Alumno alumnoBean) {
        this.alumnoBean = alumnoBean;
    }

    public Curso getCursoBean() {
        return this.cursoBean;
    }

    public void setCursoBean(Curso cursoBean) {
        this.cursoBean = cursoBean;
    }

    public Docente getDocente() {
        return this.docente;
    }

    public void setDocente(Docente docente) {
        this.docente = docente;
    }

}

entidad alumno: esta entidad está relacionada con notas, un alumno puede tener muchas notas:

package com.sistema.colegio.Pojo;

import java.io.Serializable;
import javax.persistence.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Entity
@NamedQuery(name="Alumno.findAll", query="SELECT a FROM Alumno a")
public class Alumno implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="IdAlumno")
     @GeneratedValue(strategy=GenerationType.TABLE)
    private String idAlumno;

    private String apellido;

    private int celular;

    private String correo;

    private String direccion;

    private int dni;

//  @Temporal(TemporalType.DATE)
    @Column(name="fech_nac")
    private String fechNac;

//  @Temporal(TemporalType.DATE)
    @Column(name="fech_reg")
    private String fechReg;

    private byte[] foto;

    private String grado;

    private String nombre;

    private String sexo;


    @OneToMany(mappedBy="alumnoBean",cascade = {CascadeType.PERSIST})
    private List<Nota> notas;

    public Alumno() {
    }

    public String getIdAlumno() {
        return this.idAlumno;
    }

    public void setIdAlumno(String idAlumno) {
        this.idAlumno = idAlumno;
    }

    public String getApellido() {
        return this.apellido;
    }

    public void setApellido(String apellido) {
        this.apellido = apellido;
    }

    public int getCelular() {
        return this.celular;
    }

    public void setCelular(int celular) {
        this.celular = celular;
    }

    public String getCorreo() {
        return this.correo;
    }

    public void setCorreo(String correo) {
        this.correo = correo;
    }

    public String getDireccion() {
        return this.direccion;
    }**texto en negrita**

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

    public int getDni() {
        return this.dni;
    }

    public void setDni(int dni) {
        this.dni = dni;
    }

    public String getFechNac() {
        return this.fechNac;
    }

    public void setFechNac(String fechNac) {
        this.fechNac = fechNac;
    }

    public String getFechReg() {
        return this.fechReg;
    }

    public void setFechReg(String fechReg) {
        this.fechReg = fechReg;
    }

    public byte[] getFoto() {
        return this.foto;
    }

    public void setFoto(byte[] foto) {
        this.foto = foto;
    }

    public String getGrado() {
        return this.grado;
    }

    public void setGrado(String grado) {
        this.grado = grado;
    }

    public String getNombre() {
        return this.nombre;
    }

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

    public String getSexo() {
        return this.sexo;
    }

    public void setSexo(String sexo) {
        this.sexo = sexo;
    }

    public List<Nota> getNotas() {
        return this.notas;
    }

    public void setNotas(List<Nota> notas) {
        this.notas = notas;
    }

    public Nota addNota(Nota nota) {
        getNotas().add(nota);
        nota.setAlumnoBean(this);

        return nota;
    }

    public Nota removeNota(Nota nota) {
        getNotas().remove(nota);
        nota.setAlumnoBean(null);

        return nota;
    }

    @Override
    public String toString() {
        return "Alumno [idAlumno=" + idAlumno + ", apellido=" + apellido + ", celular=" + celular + ", correo=" + correo
                + ", direccion=" + direccion + ", dni=" + dni + ", fechNac=" + fechNac + ", fechReg=" + fechReg
                + ", foto=" + Arrays.toString(foto) + ", grado=" + grado + ", nombre=" + nombre + ", sexo=" + sexo
                + ", notas=" + notas + "]";
    }


}

entidad docente: esta entidad está relacionada con notas porque un docente puede poner una nota a varios alumnos:

package com.sistema.colegio.Pojo;

import java.io.Serializable;
import java.sql.Date;
import java.util.Arrays;
import java.util.List;

import javax.persistence.*;

@Entity
@NamedQuery(name="Docente.findAll", query="SELECT d FROM Docente d")
public class Docente implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    //@GeneratedValue(strategy=GenerationType.TABLE)
     @GeneratedValue(strategy=GenerationType.TABLE)
    @Column(name="IdDocente")
    private String idDocente;

    private String apellido;

    private int celular;

    private String correo;

    private String direccion;

    private int dni;


    @Column(name="fech_nac")
    private Date fechNac;


    @Column(name="fech_reg")
    private Date fechReg;

    @Column(name="grado_inst")
    private String gradoInst;

    private String nombre;

    private String profesion;

    private String sexo;

    @Lob
    private byte[] foto;


    @OneToMany(mappedBy="docente",cascade = {CascadeType.ALL})
    private List<Nota> notas;

    public Docente() {
    }

    public String getIdDocente() {
        return this.idDocente;
    }

    public void setIdDocente(String idDocente) {
        this.idDocente = idDocente;
    }

    public String getApellido() {
        return this.apellido;
    }

    public void setApellido(String apellido) {
        this.apellido = apellido;
    }

    public int getCelular() {
        return this.celular;
    }

    public void setCelular(int celular) {
        this.celular = celular;
    }

    public String getCorreo() {
        return this.correo;
    }

    public void setCorreo(String correo) {
        this.correo = correo;
    }

    public String getDireccion() {
        return this.direccion;
    }

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

    public int getDni() {
        return this.dni;
    }

    public void setDni(int dni) {
        this.dni = dni;
    }

    public Date getFechNac() {
        return this.fechNac;
    }

    public void setFechNac(Date fechNac) {
        this.fechNac = fechNac;
    }

    public Date getFechReg() {
        return this.fechReg;
    }

    public void setFechReg(Date fechReg) {
        this.fechReg = fechReg;
    }

    public byte[] getFoto() {
        return this.foto;
    }

    public void setFoto(byte[] foto) {
        this.foto = foto;
    }

    public String getGradoInst() {
        return this.gradoInst;
    }

    public void setGradoInst(String gradoInst) {
        this.gradoInst = gradoInst;
    }

    public String getNombre() {
        return this.nombre;
    }

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

    public String getProfesion() {
        return this.profesion;
    }

    public void setProfesion(String profesion) {
        this.profesion = profesion;
    }

    public String getSexo() {
        return this.sexo;
    }

    public void setSexo(String sexo) {
        this.sexo = sexo;
    }

    public List<Nota> getNotas() {
        return this.notas;
    }

    public void setNotas(List<Nota> notas) {
        this.notas = notas;
    }

    public Nota addNota(Nota nota) {
        getNotas().add(nota);
        nota.setDocente(this);

        return nota;
    }

    public Nota removeNota(Nota nota) {
        getNotas().remove(nota);
        nota.setDocente(null);

        return nota;
    }

    @Override
    public String toString() {
        return  idDocente + apellido  + celular  + direccion + dni  + fechNac + fechReg
                + gradoInst + nombre  + profesion  + sexo
                + Arrays.toString(foto)  + notas  ;
    }


}

entidad curso: esta entidad está relacionada con curso porque curso puede tener una o varias notas y un alumno puede tener varios cursos:

package com.sistema.colegio.Pojo;

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;

@Entity
@NamedQuery(name="Curso.findAll", query="SELECT c FROM Curso c")
public class Curso implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="IdCurso")
     @GeneratedValue(strategy=GenerationType.TABLE)
    private String idCurso;

    private String nombre;


    @OneToMany(mappedBy="cursoBean",cascade = {CascadeType.PERSIST})
    private List<Nota> notas;

    public Curso() {
    }

    public String getIdCurso() {
        return this.idCurso;
    }

    public void setIdCurso(String idCurso) {
        this.idCurso = idCurso;
    }

    public String getNombre() {
        return this.nombre;
    }

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

    public List<Nota> getNotas() {
        return this.notas;
    }

    public void setNotas(List<Nota> notas) {
        this.notas = notas;
    }

    public Nota addNota(Nota nota) {
        getNotas().add(nota);
        nota.setCursoBean(this);

        return nota;
    }

    public Nota removeNota(Nota nota) {
        getNotas().remove(nota);
        nota.setCursoBean(null);

        return nota;
    }

    @Override
    public String toString() {
        return  nombre ;
    }



}

controlador notas: este controlador tiene todos los métodos de jpa

package com.sistema.colegio.Controlador;

import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;

import com.sistema.colegio.Pojo.Alumno;
import com.sistema.colegio.Pojo.Curso;
import com.sistema.colegio.Pojo.Nota;
import com.sistema.colegio.Util.JPA_UTIL;

public class NotasModel {
    private static final Logger LOGGER =Logger.getLogger("com.sistema.colegio.Controlador.DocenteModel");

    public void InsertarNotas(Nota n) {
        EntityManager manager=null;
        try {
            manager=JPA_UTIL.getEntityManager();
            manager.getTransaction().begin();
            manager.persist(n);
            //manager.persist(a);
            manager.flush();
            manager.getTransaction().commit();
            LOGGER.log(Level.INFO, "Mensaje Guardado");
            JOptionPane.showMessageDialog(null, "EXITO !!  DATOS  GUARDADOS", "MENSSAGE", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception e) {
            e.getStackTrace();
            manager.getTransaction().rollback();

            LOGGER.log(Level.INFO, "Error no se guardo"+e.getMessage());
            JOptionPane.showMessageDialog(null, "ERROR !! DATOS NO GUARDADOS", "MENSSAGE", JOptionPane.INFORMATION_MESSAGE);
        }finally {
            manager.close();
        }
    }

    public void ModificarNotas(Nota n) {
        EntityManager manager=null;
        try {

            manager=JPA_UTIL.getEntityManager();
            manager.getTransaction().begin();
            manager.merge(n);
            manager.flush();
            manager.getTransaction().commit();
            LOGGER.log(Level.INFO, "Mensaje Modificado");
            JOptionPane.showMessageDialog(null, "EXITO !!  DATOS  MODIFICADOS", "MENSSAGE", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception e) {
            manager.getTransaction().rollback();
            e.printStackTrace();
            LOGGER.log(Level.INFO, "Error no se Modificó");
            JOptionPane.showMessageDialog(null, "ERROR !! DATOS NO MODIFICADOS", "MENSSAGE", JOptionPane.INFORMATION_MESSAGE);
        }finally {
            manager.close();
        }

    }

    public void EliminarNotas(String id) {
            EntityManager manager=null;
        try {
            manager=JPA_UTIL.getEntityManager();
            Nota no=manager.find(Nota.class, id);
            manager.getTransaction().begin();
            manager.remove(no);
            manager.flush();
            manager.getTransaction().commit();
            LOGGER.log(Level.INFO, "Mensaje ELIMINADO");
        } catch (Exception e) {
            manager.getTransaction().rollback();
            e.printStackTrace();
            LOGGER.log(Level.INFO, "Error no se Elimino");
        }finally {
            manager.close();
        }
    }

    public void ListarCombo(JComboBox<Curso>cboCurso) {
        EntityManager manager=JPA_UTIL.getEntityManager();
        Iterator it=manager.createQuery("select n from Curso n").getResultList().iterator();
        Curso  c;
        try {
            while (it.hasNext()) {
                c= (Curso) it.next();
                cboCurso.addItem(c);

            }

        } catch (Exception e) {
            LOGGER.log(Level.INFO, "Error no se pudo listar");
        }
    }

}

formulario: este es el botón guardar. El error es de ahí, cuando quiero guardar una nota con un alumno, un profesor y curso que se relacionan sale el error. Me pueden ayudar por favor, soy nuevo en eso.

protected void actionPerformedBtnGuardar(ActionEvent arg0) {
        if(txtAlumno.getText().equals("")|| txtNota.getText().equals("")||txtProfesor.getText().equals("")||
                txtTema.getText().equals("")) {
            JOptionPane.showMessageDialog(this,"POR FAVOR !!! "+"\n completar todos los campos","ADVERTECNIA",JOptionPane.WARNING_MESSAGE);
        }else {
            /*CAMPOS DE OTRAS TABLAS*/
            Alumno a=new Alumno();
            a.setNombre(txtAlumno.getText());

            Docente d=new Docente();
            d.setNombre(txtProfesor.getText());

            Curso c=new Curso();
            c.setNombre(txtAlumno.getText());

            Nota ns=new Nota();
            ns.setCodigo(txtCodigo.getText());
            ns.setAlumnoBean(a);
            ns.setDocente(d);
            ns.setCursoBean(c);
            ns.setTema(txtTema.getText());
            ns.setUnidad(cboUnidad.getSelectedItem().toString());
            ns.setNota(Double.parseDouble(txtNota.getText()));
            ns.setFecha(new java.sql.Date(dtFecha.getDate().getTime()));
            n.InsertarNotas(ns);
        }
    }

    private void ListarCombo (JComboBox cboCurso) {
        n.ListarCombo(cboCurso);
    }

1 respuesta 1

0

El error es que no tienes definida la relación de dependencia para JPA:

        Alumno a=new Alumno();
        a.setNombre(txtAlumno.getText());

        Docente d=new Docente();
        d.setNombre(txtProfesor.getText());

        Curso c=new Curso();
        c.setNombre(txtAlumno.getText());

        Nota ns=new Nota();
        ns.setCodigo(txtCodigo.getText());

        ns.setAlumnoBean(a);
        ns.setDocente(d);
        ns.setCursoBean(c);
        //...
        n.InsertarNotas(ns);

Has creado un nuevo alumno, un nuevo docente y un nuevo curso (ninguno de los tres tiene un ID asignado). Cuando quieres guardar la nota, se encuentra que la has asociado con otras tres entidades que desconoce y no sabe qué hacer.

Dependiendo de lo que realmente quieras hacer los pasos serían:

  • Si alguna de las tres entidades (Alumno, Docente y Curso) existen previamente, no crees objetos nuevos, obtenlas de la base de datos y rellena la nota con ellas.

  • Si quieres que se cree la nueva entidad, entonces debes marcar la acción en cascada a realizar para esa relación. Por ejemplo, si quieres que se cree el Alumno, sería algo como:

    @ManyToOne
    @JoinColumn(cascade = CascadeType.PERSIST, name="ALUMNO", referencedColumnName = "IdAlumno")
    private Alumno alumnoBean;
    

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.