Method being called twice when loading page

Asked

Viewed 654 times

0

I have a system JSF+PrimeFaces and a page where I have a datatable, this datatable is filled in as follows:

<p:dataTable value="#{tarefaBean.listar()}" id="tarefaTable"
                var="tarefa" style="margin-top: 20px"
                emptyMessage="Nenhuma Tarefa Encontrada. " rows="10"
                paginator="true">

The method tarefaBean returns a list of Tarefa, list completing the dataTable.

The problem is that every F5 or each page rendering this method is called twice, ie two queries are performed in the database.

Example of output on console:

Metodo Listarnull
Hibernate: select usuario0_.codigo as codigo1_1_0_, usuario0_.cargo as cargo2_1_0_, usuario0_.login as login3_1_0_, usuario0_.nome as nome4_1_0_, usuario0_.senha as senha5_1_0_ from tbl_usuario usuario0_ where usuario0_.codigo=?

Metodo Listarnull
Hibernate: select usuario0_.codigo as codigo1_1_0_, usuario0_.cargo as cargo2_1_0_, usuario0_.login as login3_1_0_, usuario0_.nome as nome4_1_0_, usuario0_.senha as senha5_1_0_ from tbl_usuario usuario0_ where usuario0_.codigo=?

List method:

public List<Tarefa> listar() {
        List<Tarefa> lista = new ArrayList<>();
        System.err.println("Metodo Listar" +tarefa);
        try {
            TarefaDAO tarefaDAO = new TarefaDAO();
            lista = tarefaDAO.listarPorUsuario(usuarioBean.getUsuarioLogado());
        } catch (RuntimeException e) {
            FacesUtil.adicionarMsgErro("Erro ao listar tarefas: " + e.getMessage());
        }
        return lista;
    }

OBS: My Bean is @ViewScoped

  • 1

    Techies, why don’t you make a Lazyload link that list to a Bean property? It is common for some components to call Methodexpressions more than once, take a look at this Balusc response in the OS: http://stackoverflow.com/questions/2090033/why-jsf-calls-getters-multiple-times

  • I’ll look into.

1 answer

0


Hello,

This is a standard behavior of JSF and its EL (Expression Language). The truth is that an EL method can be invoked numerous times depending on the component and life cycle, so you should avoid expensive logics within getters methods - when I speak of expensive logic I refer to database queries, web services etc!

One solution to your problem is to take the code from the getter and move it to a callback method annotated with @PostConstruct, something like:

@PostConstruct
public void init() {
    // seu código vai aqui
}

This method will be invoked after the creation of the Managed bean and after the injection of dependencies (DI) of your framework.

To better understand how EL works and other alternatives I recommend the article JSF: Don’t put expensive logic into getters methods.

A hug,

Browser other questions tagged

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