Application does not save data and only saves code

Asked

Viewed 586 times

1

I’m developing software for a video rental company with Pattern MVC design (Model-view-controller) and the problem of not saving people is occurring. It only saves people’s code and I don’t even know why it’s happening to not save customers because my source code doesn’t show errors! In Mysql database people are not checked NOT NULL.

Class VideoPessoa, layer view:

public class VideoPessoa extends javax.swing.JFrame {


    PessoaController pessoaController;
    Pessoa pessoa;




    /**
     * Creates new form Pessoa
     */
    public VideoPessoa() {
        initComponents();

        new Conexao();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
    }


private boolean salvarPessoa(){

     if (pessoaController.salvar(pessoa)) {
     JOptionPane.showMessageDialog(this, "Registro gravado com sucesso!");


    }else{

            JOptionPane.showMessageDialog(this, "Erro ao gravar os dados!", "ERRO", JOptionPane.ERROR_MESSAGE);

        }

    return true;


    }

Class PessoaController:

  public class PessoaController {

    private final PessoaDAO pessoaDAO;


    public PessoaController() {
        pessoaDAO = new PessoaDAO();


    }

    public boolean salvar(Pessoa pessoa) {
  boolean retorno ;


    retorno = pessoaDAO.salvar(pessoa);


  return retorno;
}

Class PessoaDAO, including the method of saving people:

public class PessoaDAO {

    private Connection con;

    private final String SQLINSERT = " INSERT INTO pessoa(nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade)"
            + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?) ";

    private final String SQLPESSOAPELOCODIGO = "SELECT  nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade"
            + " FROM pessoa"
            + " WHERE codigo=? ";

    private final String SQLSELECT = " SELECT  codigo, nome, endereco, bairro, sexo, telefone, celular, CPF,  uf, cidade FROM PESSOA";

    private final String SQLUPDATE = " UPDATE pessoa"
            + " SET nome = ?, "
            + " endereco = ?, "
            + " bairro   = ?, "
            + " sexo     = ?, "
            + " telefone = ?, "
            + " celular  = ?, "
            + " CPF      = ?, "

            + " uf       =?, "
            + " cidade   =?, "
            + " WHERE codigo = ?";
    private final String SQLDELETE = "DELETE FROM pessoa"
            + " WHERE codigo = ?";

    private PreparedStatement psInsert, sqlPessoaPeloCodigo, sqlSelect, sqlUpdate, sqlDelete;

    public PessoaDAO() {

        con = Conexao.getConnection();
        try {
            psInsert = con.prepareStatement(SQLINSERT);
            sqlPessoaPeloCodigo = con.prepareStatement(SQLPESSOAPELOCODIGO);
            sqlSelect = con.prepareStatement(SQLSELECT);
            sqlUpdate = con.prepareStatement(SQLUPDATE);
            sqlDelete = con.prepareStatement(SQLDELETE);
        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

    }



public Pessoa getPessoaPeloCodigo(int codigo) {

        Pessoa pessoa = null;

        try {
            sqlPessoaPeloCodigo.setInt(1, codigo);
            ResultSet rs = sqlPessoaPeloCodigo.executeQuery();

            if (rs.next()) {
                //Instancia o novo filme
                pessoa = new Pessoa();

                //Seta as informações no filme
                pessoa.setCodigo(rs.getInt("codigo"));
                pessoa.setNome(rs.getString("nome"));
                pessoa.setEndereco(rs.getString("endereco"));
                pessoa.setBairro(rs.getString("bairro"));
                pessoa.setSexo(rs.getString("sexo"));
                pessoa.setTelefone(rs.getString("telefone"));
                pessoa.setCelular(rs.getString("celular"));
                pessoa.setCPF(rs.getString("CPF"));

                pessoa.setUf(rs.getString("uf"));
                pessoa.setCidade(rs.getString("cidade"));

            }
        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return pessoa;
    }

 public boolean salvar(Pessoa pessoa) {
        boolean retorno = false;

        try {
            psInsert.setString(1, pessoa.getNome());
            psInsert.setString(2, pessoa.getEndereco());
            psInsert.setString(3, pessoa.getBairro());
            psInsert.setString(4, pessoa.getSexo());
            psInsert.setString(5, pessoa.getTelefone());
            psInsert.setString(6, pessoa.getCelular());
            psInsert.setString(7, pessoa.getCPF());
            psInsert.setString(8, pessoa.getUf());
            psInsert.setString(9, pessoa.getCidade());

            psInsert.executeUpdate();
            retorno = true;

        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return retorno;
    }

Class Conexao:

public class Conexao {

    private static Connection con;

    public Conexao() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sistemavideolocadora2", "root", "1234");

            System.out.println(" Conexão obtida!!! ");

        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);

            System.out.println(" Conexão estabelecida com sucesso!!! ");
        }
    }

    public static Connection getConnection() {
        return con;


    }

    public static void closeConnection() {
        try {
            con.close();

            System.out.println(" Conexão fechada!!! ");
        } catch (SQLException ex) {
            Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);

            System.out.println(" Conexão finalizada com sucessso!!! ");
        }
    }


}

2 answers

3

You did not set values in the person object, at least I did not find the sets methods in the code:

    public VideoPessoa() {
        initComponents();

        new Conexao();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
    }


    private boolean salvarPessoa(){

     if (pessoaController.salvar(pessoa)) {
     JOptionPane.showMessageDialog(this, "Registro gravado com sucesso!");
ETC...

So it passes personnController.save(empty), the correct one would be:

    public VideoPessoa() {
        initComponents();

        new Conexao();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
        pessoa.setnome('alguem');
        pessoa.settelefone('(11) 999991111');
    }


    private boolean salvarPessoa(){

     if (pessoaController.salvar(pessoa)) {
     JOptionPane.showMessageDialog(this, "Registro gravado com sucesso!");
ETC...

I don’t know if the syntax is right, any error in the answer please inform, thank you.

  • I think that’s one of the problems, as he said himself when he put a sysout in the save methodPessoa() this is displayed: Person: Person{name=null, address=null, neighborhood=null, sex=null, phone=null, cell=null, CPF=null, code=0, city=null, Uf=null, person=null} `

  • 1

    @Techies, should be and only does not return error because it should be all not null and auto primary incremental key in the database.

  • Yes I thought about it too, but his code is very "messy" I couldn’t get it right

  • @Tiagooliveiradefrost this, but the attributes of the person are marked [tag:null].

  • 1

    @Techies gives discount I’m beginner yet!

  • @Tiagooliveiradefreitas It was what was missing to save the attributes of my person and I did not know that need to set them before my insertion. Thanks a lot for the answer!

Show 1 more comment

2


I refactored your code. Whenever possible, use the syntax Try-with-Resources with resources that must be adequately closed such as Connection, PreparedStatement and ResultSet. This syntax ensures that they will be closed properly with minimal programming effort on the part of the programmer. Avoid keeping these resources open longer than necessary unless you have a very strong reason to do so (and in your case, there is no).

Also, the way to notify the occurrence of a problem is with the release of exceptions. Do not return true; whether it worked and return false; if it was a mistake, because the purpose for which the exceptions exist is exactly so that you don’t have to do it, then learn to use them. In addition, the exception can carry more information about the error that would not be possible only with a simple false.

Also make sure to fill in all the data of Pessoa in the view, as explained by several colleagues in the comments in the question.

This way, your code looks like this:

/**
 * Classe que sinaliza a ocorrência de uma falha na persistência da aplicação.
 */
public class PersistenciaException extends Exception {

    /**
     * Construtor da exceção.
     * @param message A mensagem de erro.
     * @param cause A causa do erro.
     */
    public PersistenciaException(String message, Throwable cause) {
        super(message, cause);
    }
}
public class Conexao {

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    private Conexao() {
        throw new UnsupportedOperationException("Esta classe não deve ser instanciada.");
    }

    public static Connection openConnection() {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/sistemavideolocadora2", "root", "1234");
    }
}
public class PessoaDAO {

    private final String SQLINSERT = " INSERT INTO pessoa(nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade)"
            + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?) ";

    private final String SQLPESSOAPELOCODIGO = "SELECT nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade"
            + " FROM pessoa"
            + " WHERE codigo = ?";

    private final String SQLSELECT = "SELECT codigo, nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade FROM PESSOA";

    private final String SQLUPDATE = "UPDATE pessoa"
            + " SET nome = ?,"
            + " endereco = ?,"
            + " bairro   = ?,"
            + " sexo     = ?,"
            + " telefone = ?,"
            + " celular  = ?,"
            + " CPF      = ?,"
            + " uf       = ?,"
            + " cidade   = ?,"
            + " WHERE codigo = ?";

    private final String SQLDELETE = "DELETE FROM pessoa"
            + " WHERE codigo = ?";

    public PessoaDAO() {
    }

    public Pessoa getPessoaPeloCodigo(int codigo) throws PersistenciaException {
        try (
            Connection con = Conexao.openConnection();
            PreparedStatement ps = con.prepareStatement(SQLPESSOAPELOCODIGO)
        ) {
            ps.setInt(1, codigo);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) return null; // Não encontrou.
                // Instancia a nova pessoa.
                Pessoa pessoa = new Pessoa();

                // Seta as informações na pessoa
                pessoa.setCodigo(rs.getInt("codigo"));
                pessoa.setNome(rs.getString("nome"));
                pessoa.setEndereco(rs.getString("endereco"));
                pessoa.setBairro(rs.getString("bairro"));
                pessoa.setSexo(rs.getString("sexo"));
                pessoa.setTelefone(rs.getString("telefone"));
                pessoa.setCelular(rs.getString("celular"));
                pessoa.setCPF(rs.getString("CPF"));
                pessoa.setUf(rs.getString("uf"));
                pessoa.setCidade(rs.getString("cidade"));
                return pessoa;
            }
        } catch (SQLException ex) {
            throw new PersistenciaException("Problema de SQL na consulta de pessoa por código.", ex);
        }
    }

    public void salvar(Pessoa pessoa) throws PersistenciaException {
        try (
            Connection con = Conexao.openConnection();
            PreparedStatement psInsert = con.prepareStatement(SQLINSERT)
        ) {
            psInsert.setString(1, pessoa.getNome());
            psInsert.setString(2, pessoa.getEndereco());
            psInsert.setString(3, pessoa.getBairro());
            psInsert.setString(4, pessoa.getSexo());
            psInsert.setString(5, pessoa.getTelefone());
            psInsert.setString(6, pessoa.getCelular());
            psInsert.setString(7, pessoa.getCPF());
            psInsert.setString(8, pessoa.getUf());
            psInsert.setString(9, pessoa.getCidade());

            psInsert.executeUpdate();
        } catch (SQLException ex) {
            throw new PersistenciaException("Problema de SQL na inserção de pessoa.", ex);
        }
    }
}
public class PessoaController {
    private final PessoaDAO pessoaDAO;

    public PessoaController() {
        pessoaDAO = new PessoaDAO();
    }

    public void salvar(Pessoa pessoa) throws PersistenciaException {
        pessoaDAO.salvar(pessoa);
    }
}
public class VideoPessoa extends javax.swing.JFrame {
    private final PessoaController pessoaController;
    private Pessoa pessoa;

    /**
     * Creates new form Pessoa
     */
    public VideoPessoa() {
        initComponents();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
    }

    private void salvarPessoa() {
        try {
            pessoaController.salvar(pessoa);
            JOptionPane.showMessageDialog(this, "Registro gravado com sucesso!");
        } catch (PersistenciaException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao gravar os dados!", "ERRO: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
        }
    }

    // Resto da classe....
}
  • 1

    You opened my eyes and gave me a beautiful explanation that many of my college professors didn’t explain it to me during my college. ** I will follow your advice and thanks! **

  • The word Persistenciaexception is giving error and displayed a message that she has no javadoc and that had create the class for her. Well I don’t know how to do it.

  • @Igorcontini You should not be required to create any javadoc. But if for some reason you are obliged to do so, I updated the reply with this javadoc.

  • Beauty and thanks man!

  • Why shouldn’t the class be instantiated? I need it to be instantiated!

  • @Igorcontini This question is from last year, so I don’t really remember what you wanted. Well, the only class that is not instantiable here is the Conexao, the reason is because an instance of it would serve no purpose, since the only method of this class that makes sense to be called is static. However, if this class undergoes any kind of change, it may need to become unstable.

  • Well I need it to be instantiated for my DAO and when I spin my system, it makes that mistake: throw new UnsupportedOperationException("Esta classe não deve ser instanciada.")

  • @Igorcontini This exception is thrown from inside the constructor. If you really need to instantiate this, just delete the line from the throw that’s inside the builder. However, remember that it usually only makes sense to instantiate a class if you are going to use its (non-static) instance methods. The purpose of this exception is just not to let you do a meaningless operation (instantiating a class for which the instance serves no purpose). However, if the instances now make sense, this exception would no longer be necessary or desirable and it would be enough to remove the throw.

  • I erased the line and caused another error: java.lang.RuntimeException: Uncompilable source code - unreported exception util.PersistenciaException; must be caught or declared to be thrown

  • @Igorcontini I think you’re using the eclipse and making hot-deploy. Recompile the entire application and tell me what the build error is and where it happens.

Show 6 more comments

Browser other questions tagged

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