NullPointerException when updating in JPA

0

I have the following code to update the values of an object that are displayed in a table:

public class AgendaJPADAOImpl implements AgendaJPADAO, Serializable {

EntityManagerFactory emf = Persistence.createEntityManagerFactory("AGENDAJPAPU");
EntityManager em = emf.createEntityManager();

    public void actualizar(Contacto c, int id) {
        em.getTransaction().begin();
        em.find(Contacto.class, id);
        em.merge(c);
        em.getTransaction().commit();
    }
}

The following code is the class where I perform the operations with the update method and others:

package comm.agendaJPA.controlador;

import comm.agendaJPA.dao.factory.AgendaJPAFactory;
import comm.agendaJPA.dao.interfaces.AgendaJPADAO;
import comm.agendaJPA.interfaz.*;
import comm.agendaJPA.modelo.Contacto;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

public class AgendaJPAControlador implements ActionListener {

private final AgendaJPAFactory factory = new AgendaJPAFactory();
private final AgendaJPADAO agendaDAO = factory.agendaJPAFactory();
private final AgendaJPAdmin agendaJPAdmin;
private final AgendaJPAContacto agendaJPAContacto;
Contacto contacto = new Contacto();
FuncionesControlador funciones = new FuncionesControlador();

public AgendaJPAControlador(AgendaJPAdmin agendaJPAdmin, AgendaJPAContacto agendaJPAContacto) {
    this.agendaJPAdmin = agendaJPAdmin;
    this.agendaJPAContacto = agendaJPAContacto;
}

private enum Componentes {
    getTxtBuscar_Contacto,
    getBtnAgr_Contacto,
    getTablaContactos,
    getSubmenu_Modificar,
    getSubmenu_Eliminar,
    getBtnGuardar,
    getBtnModificar
}

public void limpiarCampos() {
    this.agendaJPAContacto.getTxtNombre().setText("");
    this.agendaJPAContacto.getTxtApellido().setText("");
    this.agendaJPAContacto.getTxtMovil().setText("");
    this.agendaJPAContacto.getTxtCasa().setText("");
    this.agendaJPAContacto.getTxtPersonal().setText("");
    this.agendaJPAContacto.getTxtTrabajo().setText("");
    this.agendaJPAContacto.getTxtPanelDireccion().setText("");
}

public void abrirAgendaJPA() {
    this.funciones.listarTabla(agendaJPAdmin.getTablaContactos());
    this.agendaJPAdmin.setTitle("AGENDA");
    this.agendaJPAdmin.setLocationRelativeTo(agendaJPAdmin);
    this.agendaJPAdmin.setVisible(true);

    this.agendaJPAdmin.getTablaContactos().addMouseListener(this);
    this.agendaJPAdmin.getTxtBuscar_Contacto().addActionListener(this);
    this.agendaJPAdmin.getTxtBuscar_Contacto().setActionCommand("getTxtBuscar_Contacto");
    this.agendaJPAdmin.getBtnAgr_Contacto().addActionListener(this);
    this.agendaJPAdmin.getBtnAgr_Contacto().setActionCommand("getBtnAgr_Contacto");
    this.agendaJPAdmin.getSubmenu_Modificar().addActionListener(this);
    this.agendaJPAdmin.getSubmenu_Modificar().setActionCommand("getSubmenu_Modificar");
    this.agendaJPAdmin.getSubmenu_Eliminar().addActionListener(this);
    this.agendaJPAdmin.getSubmenu_Eliminar().setActionCommand("getSubmenu_Eliminar");
    this.agendaJPAContacto.getBtnGuardar().addActionListener(this);
    this.agendaJPAContacto.getBtnGuardar().setActionCommand("getBtnGuardar");
    this.agendaJPAContacto.getBtnModificar().addActionListener(this);
    this.agendaJPAContacto.getBtnModificar().setActionCommand("getBtnModificar");
}

@Override
public void actionPerformed(ActionEvent evento) {

    switch (Componentes.valueOf(evento.getActionCommand())) {

        //Eventos ventana AgendaJPAdmin
        case getBtnAgr_Contacto:
            this.limpiarCampos();
            this.agendaJPAContacto.setTitle("NUEVO CONTACTO");
            this.agendaJPAContacto.getBtnModificar().setVisible(false);
            this.agendaJPAContacto.getBtnGuardar().setVisible(true);
            this.agendaJPAContacto.setVisible(true);
            this.agendaJPAContacto.setLocationRelativeTo(agendaJPAdmin);
            break;

        //Eventos JPopupMenu de la ventana AgendaJPAdmin
        case getSubmenu_Modificar:
            this.limpiarCampos();
            this.agendaJPAContacto.setTitle("MODIFICAR CONTACTO");
            int filaSeleccionada = this.agendaJPAdmin.getTablaContactos().getSelectedRow();

            if (filaSeleccionada >= 0) {

                List<Contacto> contactosMod = agendaDAO.extraerTodos();
                Contacto contactoMostrado = contactosMod.get(filaSeleccionada);

                this.agendaJPAContacto.getTxtNombre().setText(contactoMostrado.getNombre());
                this.agendaJPAContacto.getTxtApellido().setText(contactoMostrado.getApellido());
                this.agendaJPAContacto.getTxtMovil().setText(contactoMostrado.getMovil().toString());
                this.agendaJPAContacto.getTxtCasa().setText(contactoMostrado.getCasa().toString());
                this.agendaJPAContacto.getTxtPersonal().setText(contactoMostrado.getPersonal());
                this.agendaJPAContacto.getTxtTrabajo().setText(contactoMostrado.getTrabajo());
                this.agendaJPAContacto.getTxtPanelDireccion().setText(contactoMostrado.getDireccion());

                this.agendaJPAContacto.setLocationRelativeTo(agendaJPAdmin);
                this.agendaJPAContacto.getBtnGuardar().setVisible(false);
                this.agendaJPAContacto.getBtnModificar().setVisible(true);
                this.agendaJPAContacto.setVisible(true);

            } else {
                //No se ha implementado nada
            }
            break;

        case getSubmenu_Eliminar:
            int filaEliminar = this.agendaJPAdmin.getTablaContactos().getSelectedRow();

            if (filaEliminar >= 0) {
                int opcionEliminar = JOptionPane.showConfirmDialog(agendaJPAdmin,
                        "Desea eliminar este contacto?", "Borrar", JOptionPane.YES_NO_OPTION);

                if (opcionEliminar == JOptionPane.YES_OPTION) {
                    List<Contacto> contactos = this.agendaDAO.extraerTodos();
                    Contacto contactoEliminar = contactos.get(filaEliminar);

                    if (contactoEliminar != null) {
                        this.agendaDAO.borrar(contactoEliminar);
                        this.funciones.listarTabla(this.agendaJPAdmin.getTablaContactos());
                    } else {
                        JOptionPane.showMessageDialog(agendaJPAdmin, "No se pudo eliminar el contacto");
                    }
                } else {
                    //No se ha implementado nada
                }
            }
            break;
        case getBtnGuardar:
            String nombre = agendaJPAContacto.getTxtNombre().getText();
            String apellido = agendaJPAContacto.getTxtApellido().getText();
            String movil = agendaJPAContacto.getTxtMovil().getText();
            String casa = agendaJPAContacto.getTxtCasa().getText();
            String personal = agendaJPAContacto.getTxtPersonal().getText();
            String trabajo = agendaJPAContacto.getTxtTrabajo().getText();
            String direccion = agendaJPAContacto.getTxtPanelDireccion().getText();

            String contactoNuevo = nombre + apellido + movil + casa + personal
                    + trabajo + direccion;
            if (contactoNuevo != null) {
                this.agendaDAO.guardar(new Contacto(nombre, apellido,
                        Integer.valueOf(movil), Integer.parseInt(casa),
                        personal, trabajo, direccion));
                this.funciones.listarTabla(this.agendaJPAdmin.getTablaContactos());
            } else {
                //No se ha implementado nada
            }
            this.limpiarCampos();
            this.agendaJPAContacto.dispose();
            break;

        case getBtnModificar:
            int filaMod = this.agendaJPAdmin.getTablaContactos().getSelectedRow();

            if (filaMod >= 0) {
                String nombreMod = agendaJPAContacto.getTxtNombre().getText();
                String apellidoMod = agendaJPAContacto.getTxtApellido().getText();
                String movilMod = agendaJPAContacto.getTxtMovil().getText();
                String casaMod = agendaJPAContacto.getTxtCasa().getText();
                String personalMod = agendaJPAContacto.getTxtPersonal().getText();
                String trabajoMod = agendaJPAContacto.getTxtTrabajo().getText();
                String direccionMod = agendaJPAContacto.getTxtPanelDireccion().getText();

                List<Contacto> contactos = agendaDAO.extraerTodos();
                Contacto contactoMod = contactos.get(filaMod);

                int id = contacto.getId();
                this.agendaDAO.actualizar(new Contacto(nombreMod, apellidoMod,
                        Integer.valueOf(movilMod), Integer.parseInt(casaMod),
                        personalMod, trabajoMod, direccionMod), id);

                this.funciones.listarTabla(this.agendaJPAdmin.getTablaContactos());
                this.agendaJPAContacto.dispose();
                this.limpiarCampos();
            }
            break;
    }
}

My class Contact , which is the POJO of the program is this and from where I look for the contact id when wanting to update the object is the following:

package comm.agendaJPA.modelo;

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

@Entity(name = "ContactoAgenda")
@Table(name = "contacto")
public class Contacto implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "fecha")
@Temporal(TemporalType.TIMESTAMP)
private Calendar fecha;
@Column(name = "nombre")
private String nombre;
@Column(name = "apellido")
private String apellido;
@Column(name = "movil")
private Integer movil;
@Column(name = "casa")
private Integer casa;
@Column(name = "personal")
private String personal;
@Column(name = "trabajo")
private String trabajo;
@Column(name = "direccion")
private String direccion;

public Contacto() {
}

public Contacto(String nombre, String apellido, int movil, int casa, String personal, String trabajo, String direccion) {
    this.nombre = nombre;
    this.apellido = apellido;
    this.movil = movil;
    this.casa = casa;
    this.personal = personal;
    this.trabajo = trabajo;
    this.direccion = direccion;
}

public Integer getId() {
    return id;
}

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

public Calendar getFecha() {
    return fecha;
}

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

public String getNombre() {
    return nombre;
}

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

public String getApellido() {
    return apellido;
}

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

public Integer getMovil() {
    return movil;
}

public void setMovil(Integer movil) {
    this.movil = movil;
}

public Integer getCasa() {
    return casa;
}

public void setCasa(Integer casa) {
    this.casa = casa;
}

public String getPersonal() {
    return personal;
}

public void setPersonal(String personal) {
    this.personal = personal;
}

public String getTrabajo() {
    return trabajo;
}

public void setTrabajo(String trabajo) {
    this.trabajo = trabajo;
}

public String getDireccion() {
    return direccion;
}

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

}

When performing operations, show this printStack :

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at comm.agendaJPA.controlador.AgendaJPAControlador.actionPerformed(AgendaJPAControlador.java:192)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

The line 192 that the printStacke mentions is this:

int id = contacto.getId(); Here I'm looking for the contact id

Instead of looking for the id of the object I could pass filaMod to the method and it would work but the previous object is still present when I do it, ergo, it is not updated , only saved again this time with the new values.

    
asked by David Calderon 25.10.2016 в 13:56
source

2 answers

1

As I put in the comments, your problem is that when you do Contacto contacto = new Contacto(); the properties of this will always be null (unless you initialize it by passing the parameters with the other constructor you have or you do a setId() ) . With the code you have, I think this could work for you:

List<Contacto> contactos = agendaDAO.extraerTodos();
Contacto contactoMod = contactos.get(filaMod);
contactoMod.setNombre(agendaJPAContacto.getTxtNombre().getText());
contactoMod.setApellido(agendaJPAContacto.getTxtApellido().getText());
contactoMod.setMovil(Integer.valueOf(agendaJPAContacto.getTxtMovil().getText()));
contactoMod.setCasa(Integer.parseInt(agendaJPAContacto.getTxtCasa().getText()));
contactoMod.setPersonal(agendaJPAContacto.getTxtPersonal().getText())
contactoMod.setTrabajo(agendaJPAContacto.getTxtTrabajo().getText());
contactoMod.setDireccion(agendaJPAContacto.getTxtPanelDireccion().getText());

this.agendaDAO.actualizar(contactoMod, contactoMod.getId());

Even if you do it this way you could change the update method and send it only the contact object, which already contains the id you need

public void actualizar(Contacto c){
    em.getTransaction().begin();
    em.merge(c);
    em.getTransaction().commit();
}

With JPA you should not need the find method to update a record since when sending the contact object it should update it correctly by having the same id

    
answered by 26.10.2016 / 12:47
source
2

Your problem is that you never assign an id before reading it. You have to use setId() before using getId or add a constructor that assigns value to it. When using new Contacto() and put just after contacto.getId() you will find an uninitialized variable.

Either you do that or you forgot to bring the variable contacto loaded from another site.

    
answered by 25.10.2016 в 19:11