Method being called twice while loading page

0

I have a JSF+PrimeFaces system and a page where I have a dataTable, this dataTable is populated as follows:

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

The tarefaBean method returns a list of Tarefa , list that fills dataTable .

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

Example of the output from the 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=?

Listing 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

    
asked by anonymous 27.07.2015 / 20:47

1 answer

0

Hello,

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

One solution to your problem is to get the getter code 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 dependency injection (DI) of your framework.

To better understand how EL works and other alternatives I recommend the article JSF: Do not put expensive logic in getters methods .

A hug,

    
07.06.2016 / 19:17