java – Object getting null in the middle of the process

Question:

I'm developing a system using Java, Maven, Hibernate, PrimeFaces and MySQL database. Within this system, I created a program to record the amount of rain that occurs in the day.

My Pluviometro table has the fields for the (auto increment code, location, date and amount of rain).

When I initialize the canvas, I have an @PostContruct that initializes my Pluviometro object. After initialization, I fill in the 3 fields in the table and click on save.

When clicking the "record" button it calls the method to save the data, but the Pluviometro object reaches null . Can anyone give me a hint of what might be going on?

@PostConstruct
private void startDeTela(){
    PluviometroDAO pluviometroDAO = new PluviometroDAO();
    pluviometros = pluviometroDAO.listar("dataDeApontamento");
    pluviometro = new Pluviometro();
    carregaSelectItens();
}

public void novo(){
    pluviometro = new Pluviometro();
}

public void salvar(){
    PluviometroDAO pluviometroDAO = new PluviometroDAO();
    try{
        pluviometroDAO.merge(pluviometro);
        Messages.addGlobalInfo("Apontamento Registrado Com Sucesso.");
        novo();
    }catch(RuntimeException erro){
        erro.printStackTrace();
    }
}

Answer:

  1. Make life easier for those who are trying to help you and put the complete source code, along with the xhtml.
  2. In the save method you are merging the rain gauge object. This object must be declared in the class scope along with gets and sets. And in xhtml you point each field to the attributes of that object.
  3. If you have CDI as a dependency in the project, use it to inject the PluviometroDAO object with the @Inject annotation. Note that in the code presented there are 2 lines exactly the same to instantiate it.
  4. If you don't use CDI in the project, create a variable with global scope and initialize it only once via @PostConstruct. This way, you avoid code replication.
  5. In a managed bean it is not interesting to inject a DAO, considering "design standards" . The ideal would be to have the following structure (Managed Bean > Controller > DAO)

If with these instructions you are unable to resolve the issue at hand. Take a look at this link with a working project.

Scroll to Top
AllEscort