Error changing record in table

Asked

Viewed 37 times

0

I can change manually, but in the error project.. The Error:

Cannot add or update a child row: a foreign key constraint fails (sistema.veiculo, CONSTRAINTveiculo_ibfk_1FOREIGN KEY (fk_idassociado) REFERENCESassociado(ID_ASSOCIADO`) ON DELETE CASCADE)

edit screen:

public class Edit_Veiculo extends javax.swing.JFrame {

     Conexao CONEXAO = new Conexao();
    DefaultListModel MODELO;
    int Enter = 0;

     String [] Codig;


    public Edit_Veiculo() {
        initComponents();

         //tela maximizada
        this.setExtendedState(MAXIMIZED_BOTH);
        Lista.setVisible(false);
        //listagem
        CONEXAO.conecta();
        MostraPesquisa();

        MODELO = new DefaultListModel();
        Lista.setModel(MODELO);
    }

 private void PesquisaPlacaMousePressed(java.awt.event.MouseEvent evt) {                                           
        MostraPesquisa();
        Lista.setVisible(false);
    }                               

private void PesquisaPlacaActionPerformed(java.awt.event.ActionEvent evt) {                                              
        Lista.setVisible(false);
        Enter = 1;
    }                                             

    private void PesquisaPlacaKeyReleased(java.awt.event.KeyEvent evt) {                                          
        if(Enter == 0)
        ListadePesquisa();
        else
        Enter = 0;
    }                                         

    private void ListaMousePressed(java.awt.event.MouseEvent evt) {                                   
        MostraPesquisa();
        Lista.setVisible(false);
    }                       


    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                          
try{
        Associado associado = new Associado();
        Veiculo veiculo = new Veiculo();
        VeiculoDao vdao = new VeiculoDao();

        veiculo.setIdveiculo(Integer.parseInt(idveiculo.getText()));

        veiculo.setPlaca(placa.getText());
        veiculo.setRenavam(renavam.getText());
        veiculo.setMarca(marca.getText());
        veiculo.setModelo(modelo.getText());
        veiculo.setChassi(chassi.getText());
        veiculo.setAno(Integer.parseInt(ano.getText()));
        veiculo.setCor(cor.getText());        


        veiculo.setAssociado(associado);

        vdao.alterarVeiculo(veiculo);
}catch (Exception ex){
     Logger.getLogger(Edit_Veiculo.class.getName()).log(Level.SEVERE, null, ex);
           JOptionPane.showMessageDialog(null, "Erro ao alterar." + ex);
}
    }                                       

public void ListadePesquisa(){
 try {
            CONEXAO.executaSQL("SELECT * FROM veiculo where placa like '" + PesquisaPlaca.getText() + "%' ORDER BY placa");
            MODELO.removeAllElements();
            int v = 0;
            Codig = new String[4];
            while (CONEXAO.resultset.next() & v < 4) {
                MODELO.addElement(CONEXAO.resultset.getString("placa"));

                Codig[v] = CONEXAO.resultset.getString("idveiculo");
                v++;
            }
            if (v >= 1) {
                Lista.setVisible(true);
            } else {
                Lista.setVisible(false);
            }

            ResultadoPesquisa();
        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao listar dados" + erro);
        }    
}

 public void MostraPesquisa() {
        int Linha = Lista.getSelectedIndex();
        if (Linha >= 0) {
            CONEXAO.executaSQL("SELECT * FROM veiculo where idveiculo = "+Codig[Linha]+" ");
            ResultadoPesquisa();
        }

    }

 public void ResultadoPesquisa() {

        try {
            CONEXAO.resultset.first();
           //dados associado
            idveiculo.setText(CONEXAO.resultset.getString("idveiculo"));
            numcota.setText(CONEXAO.resultset.getString("fk_idassociado"));
            placa.setText(CONEXAO.resultset.getString("placa"));
            renavam.setText(CONEXAO.resultset.getString("renavam"));
            marca.setText(CONEXAO.resultset.getString("marca"));
            modelo.setText(CONEXAO.resultset.getString("modelo"));
            chassi.setText(CONEXAO.resultset.getString("chassi"));
            ano.setText(CONEXAO.resultset.getString("ano"));
            cor.setText(CONEXAO.resultset.getString("cor"));


        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao pesquisar." + erro);
        }
    }

}

tables:

CREATE TABLE `associado` (
  `ID_ASSOCIADO` int(255) NOT NULL,
  `NOME` varchar(50) NOT NULL,
  `CPF` varchar(14) NOT NULL,
  `RG` varchar(13) NOT NULL,
  `CELULAR` int(30) NOT NULL,
  `TELEFONE` int(30) NOT NULL,
  `DATA_NASC` varchar(10) NOT NULL,
  `ESTADO` char(2) NOT NULL,
  `CIDADE` varchar(50) NOT NULL,
  `CEP` int(9) NOT NULL,
  `ENDERECO` varchar(50) NOT NULL,
  `BAIRRO` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `veiculo` (
  `idveiculo` int(11) NOT NULL,
  `fk_idassociado` int(11) NOT NULL,
  `placa` varchar(7) NOT NULL,
  `renavam` varchar(11) NOT NULL,
  `marca` varchar(100) NOT NULL,
  `modelo` varchar(50) NOT NULL,
  `chassi` varchar(8) NOT NULL,
  `ano` int(4) NOT NULL,
  `cor` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `associado`
  ADD PRIMARY KEY (`ID_ASSOCIADO`);


ALTER TABLE `veiculo`
  ADD PRIMARY KEY (`idveiculo`),
  ADD KEY `fk_idassociado` (`fk_idassociado`);

 ALTER TABLE `veiculo`
      MODIFY `idveiculo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;

ALTER TABLE `veiculo`
      ADD CONSTRAINT `veiculo_ibfk_1` FOREIGN KEY (`fk_idassociado`) REFERENCES `associado` (`ID_ASSOCIADO`)
      ON DELETE CASCADE;

method alter:

public void alterarEngate(Engate eng) {
        Transaction tx = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            tx = session.beginTransaction();
            session.update(eng);
            session.getTransaction().commit();
            JOptionPane.showMessageDialog(null, "Alterado com sucesso!");
        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            session.flush();
            session.close();
        }
    }

screen print:

inserir a descrição da imagem aqui

  • it seems that the problem is in the entity mapping in the vehicle Constraint

  • Considering Associado associado = new Associado();. And then veiculo.setAssociado(associado); the impression that passes is that the associated object veiculo is 0. You can check this?

  • the problem is in the code because I can change the records manually..

1 answer

0


Good afternoon,

I think you could put more of your code. The whole method, for example. But apparently you are trying to save or update a vehicle registration with an associate registration that does not exist.

First of all:

    veiculo.setAssociado(veiculo.getAssociado());

It does not make sense what is written in the above section. Vc is defining the associated vehicle with the associated that the vehicle itself already owns. (?)

Getting back to your problem. I suggest you debug your code, see the ID of the member being set in your vehicle. With the ID, search the database for it to confirm it actually exists. If it does not exist, the problem is solved: The foreign key (ID_ASSOCIADO) does not exist in the associated table. You will have to do some treatment regarding this or change your logic.

But try to put more of your code in for the staff to help you better.

  • Thanks for the help but check if the id exists in the parent table was the first thing I did, and there is yes! I will update the question with the codes..

  • At what point in the code are you defining the associate? Pq looking there in the code when you do vehicle.setAssociated(associated);' the value of associate is empty. Nothing was assigned to him after the Associate declaration = new Associate();

  • Don’t need that line? Sorry, I’m a beginner..

  • Yes you do, but your object is empty. You simply created it. Try to put values in it so that it can be located in the bank. After Associate = new Associate(); put the value of the associate that is in the database and will be searched, for example: associate.setID(1);

  • Got it! Thanks for the help!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.