Quantcast
Channel: Error al guardar una Imagen en JPA - JAVA - Stack Overflow en español
Viewing all articles
Browse latest Browse all 2

Error al guardar una Imagen en JPA - JAVA

$
0
0

Tengo un formulario de Alumnos que al intentar guardar me sale error en la imagen ,porfavor me pueden ayudar, saludos

Clase Alumno

@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;@Column(name="fech_nac")private String fechNac;@Column(name="fech_reg")private String fechReg;@Lobprivate 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;}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;}@Overridepublic 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 +"]";}

}

Controlador Alumno

En esta parte se declara todos los metodos del mantenimiento (eliminar ,actualizar, editar, litar)Estos metodos estan referenciados con JPA PARA PODER AUTOMATIZAR nuestra aplicacion

public class AlumnoModel {public void GuardarDatos(Alumno a) {    EntityManager manager=null;    try {        manager=JPA_UTIL.getEntityManager();        manager.getTransaction().begin();        manager.persist(a); // Genera el JPQL(consulta sql) internamente        manager.flush();// Enviar en cola(pueden haber varios SQL)        manager.getTransaction().commit(); // Envia a la BD    } catch (Exception e) {        manager.getTransaction().rollback();    }finally {        manager.close();    }}}

Entidad Alumno

En esta parte de codigo del guardado le paso de parametro la imagen en byte eso estaria bien

 public class AlumnoDAO {private AlumnoModel m = new AlumnoModel();private Alumno a = new Alumno();public Integer totalRegistro;//private String mensaje = ""; private static final Logger LOGGER =Logger.getLogger("com.sistema.colegio.Dao.AlumnoDAO");public int InsertarDatos(String idAlumno, String nombre, String apellido, int dni, int celular, String fechNac,        String fechReg, String grado, String sexo, String direccion, String correo,byte[] foto) {    int rpta=0;    try {        a.setIdAlumno(idAlumno);        a.setNombre(nombre);        a.setApellido(apellido);        a.setDni(dni);        a.setCelular(celular);        a.setFechNac(fechNac);        a.setFechReg(fechReg);        a.setGrado(grado);        a.setSexo(sexo);        a.setDireccion(direccion);        a.setCorreo(correo);        a.setFoto(foto);        m.GuardarDatos(a);    //  mensaje = "EXITO! SE REGISTRO CORRECTAMENTE";        LOGGER.log(Level.INFO, "Proceso exitoso");    } catch (Exception e) {    //  mensaje = "ERROR NO SE REGISTRO CORRECTAMENTE";        LOGGER.log(Level.INFO, "Error no se guardo");    }    return rpta;}}

Convertir Imagen en Byte

 public class ImagenConver { public static Image imagen(Icon icon) {    int w=icon.getIconWidth();    int h=icon.getIconHeight();    GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();    GraphicsDevice gd=ge.getDefaultScreenDevice();    GraphicsConfiguration gc=gd.getDefaultConfiguration();    BufferedImage bi=gc.createCompatibleImage(w,h);    Graphics2D g=bi.createGraphics();    icon.paintIcon(null, g, 0, 0);    g.dispose();    return bi;}public static byte[] tipoimagen(Image imge) {    BufferedImage bi=new    BufferedImage(imge.getWidth(null),imge.getHeight(null),BufferedImage.TYPE_INT_BGR);    Graphics g=bi.getGraphics();    g.drawImage(imge,0,0,null);    g.dispose();    ByteArrayOutputStream stream=new ByteArrayOutputStream();    try {        ImageIO.write(bi, "JPG", stream);    } catch (IOException ex) {        Logger.getLogger(ImagenConver.class.getName()).log(Level.SEVERE, "error de imagen", ex);    }    return stream.toByteArray();}}

Formulario Alumno

En esta parte del codigo es donde me marca el error de la imagen al convertirla me podrian ayudar porfavor

     protected void actionPerformedBtnAgregar(ActionEvent arg0) {       if (txtId.getText().equals("") || txtNombre.getText().equals("") ||         txtApellido.getText().equals("")            || txtDni.getText().equals("") || txtCelular.getText().equals("") ||         txtFecha.getText().equals("")            || txtReg.getText().equals("") || txtDireccion.getText().equals("") ||         txtCorreo.getText().equals("")) {        JOptionPane.showMessageDialog(null, "COMPLETAR TODOS LOS CAMPOS DEL FORMULARIO", "ERROR",                JOptionPane.ERROR_MESSAGE);    } else {        String idAlumno = txtId.getText();        String nombre = txtNombre.getText();        String apellido = txtApellido.getText();        int dni = Integer.parseInt(txtDni.getText());        int celular = Integer.parseInt(txtCelular.getText());        String fechNac = txtFecha.getText();        String fechReg = txtReg.getText();        String grado = cboGrado.getSelectedItem().toString();        if (rdbtHombre.isSelected()) {            gender = "H";        } else if (rdbtnM.isSelected()) {            gender = "M";        }        String sexo = gender;        String direccion = txtDireccion.getText();        String correo = txtCorreo.getText();        Image image = ImagenConver.imagen(FOTO.getIcon());        ImagenConver.tipoimagen(image);        int opcion = al.InsertarDatos(idAlumno, nombre, apellido, dni, celular, fechNac, fechReg,    grado, sexo,                direccion, correo,image);        if(opcion ==0) {            try {                JOptionPane.showMessageDialog(null, "Se Registro Corectamente", "",    JOptionPane.INFORMATION_MESSAGE);                limpiar();                bloquear();                btnNuevo.setEnabled(true);            } catch (Exception e) {                JOptionPane.showMessageDialog(null, "Error al Registar !!", "",     JOptionPane.INFORMATION_MESSAGE);            }        }    }}

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images