Aparente loop infinito no ManagedBean do JSF

5 respostas
F

Estou desenvolvendo uma aplicação web utilizando JSF 2.0 com Hibernate, estou tentando fazer uma chamada de um ManagedBean, para exibir uma lista de valores do banco de dados, ai esta o managed bean:

package br.salesianos.db;

import br.salesianos.modelo.Estado;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import org.hibernate.Session;

@ManagedBean
public class seuManagedBean {

    private List suaLista;    

    public List getSuaLista() {

        Session sessao = CriadorDeSessao.getSession();

        List<Estado> listado = new ArrayList();
            listado = sessao.createCriteria(Estado.class).list();
            int tamanho_lista = listado.size();
        
        
        return listado;
    }

    /**
     * @param suaLista the suaLista to set
     */
    public void setSuaLista(List suaLista) {
        this.suaLista = suaLista;
    }

    
    
}

e ai esta a pagina xhtml que exibe ele

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.prime.com.tr/ui"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      
      xmlns:f="http://java.sun.com/jsf/core">
<h:head><title>Curriculo Salesiano</title>
</h:head>
<h:body>
<div align="center">
<h1>Cadastro de Estados</h1>
<f:view>
<h:form>
    <h:dataTable border="1" var="item" value="#{seuManagedBean.suaLista}">
        <h:column>
            <h:outputText value="#{item.est_sigla}" />
        </h:column>
        <h:column>
            <h:outputText value="#{item.est_nom}" />
        </h:column>
    </h:dataTable>
    <br/><br/>
    <h:selectOneMenu value="tata">
        <f:selectItem itemValue="1" itemLabel="um"/>
        <f:selectItem itemValue="2" itemLabel="dois"/>
    </h:selectOneMenu>
    <h:selectOneMenu value="#{seuManagedBean.suaLista}">
        <f:selectItems value="#{seuManagedBean.suaLista}" var="u" itemLabel="#{u.est_nom}" itemValue="#{u.est_sigla}" />
    </h:selectOneMenu>

  <br/>
  <h:commandLink value="Voltar" action="inicio"/>
</h:form>
</f:view>

<hr/>

</div></h:body></html>

ele exibe corretamente os valores, porém demora muito pra exibir, suspeitando dessa demora fui olhar no console do tomcat pra descobrir se ele me dava alguma pista, e vi que ele parece entrar em um loop infinito(aparentemente), pois ele executa muitas vezes a query abaixo(são tantas vezes que é até dificil contar, e isso pq so tem tres valores no meu banco de dados)
apesar de parecer infinito, não é, pois depois de um tempo ele para

20828 [http-8088-1] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
20859 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Pessoas
20859 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Pessoas on table Pessoas
20859 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Estado
20859 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Estado on table Estado
20953 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Cidade
20953 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Cidade on table Cidade
20953 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Inspetoria
20953 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Inspetoria on table Inspetoria
21063 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Familia_Salesiana
21063 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Familia_Salesiana on table Familia_Salesiana
21063 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Comunidade
21063 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Comunidade on table Comunidade
21156 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Obra
21156 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Obra on table Obra
21156 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Comunidade_Obra
21156 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Comunidade_Obra on table Hist_Comunidade_Obra
21266 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Salesianos
21266 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Salesianos on table Salesianos
21266 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Separacao
21266 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Separacao on table Separacao
21359 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Separacao
21359 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Separacao on table Hist_Separacao
21359 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Parentesco
21359 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Parentesco on table Parentesco
21469 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Eventos
21469 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Eventos on table Eventos
21469 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Eventos
21469 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Eventos on table Hist_Eventos
21563 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Cursos_Especializados
21563 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Cursos_Especializados on table Cursos_Especializados
21563 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Cursos_Especializados
21563 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Cursos_Especializados on table Hist_Cursos_Especializados
21656 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Sacramentos_Ministerios
21656 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Sacramentos_Ministerios on table Sacramentos_Ministerios
21656 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Diocese
21656 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Diocese on table Diocese
21766 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Bispos
21766 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Bispos on table Bispos
21766 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Paroquia
21766 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Paroquia on table Paroquia
21859 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Diocese_Bispo
21859 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Diocese_Bispo on table Hist_Diocese_Bispo
21859 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Formacao_Religiosa
21859 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Formacao_Religiosa on table Formacao_Religiosa
21969 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Formacao_Religiosa
21969 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Formacao_Religiosa on table Hist_Formacao_Religiosa
21969 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Sistemas
21969 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Sistemas on table Sistemas
22063 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Cargo
22063 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Cargo on table Cargo
22063 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Comissao
22063 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Comissao on table Hist_Comissao
22172 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Profissoes
22172 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Profissoes on table Profissoes
22172 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Profissoes
22172 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Profissoes on table Hist_Profissoes
22266 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Tipo_Producao
22266 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Tipo_Producao on table Tipo_Producao
22266 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Producao_Intelectual
22266 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Producao_Intelectual on table Producao_Intelectual
22375 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Graduacao
22375 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Graduacao on table Graduacao
22375 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Graduacao
22375 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Graduacao on table Hist_Graduacao
22469 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Comunidade
22469 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Comunidade on table Hist_Comunidade
22469 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Salesianos_Obra
22469 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Salesianos_Obra on table Hist_Salesianos_Obra
22563 [http-8088-1] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: br.salesianos.modelo.Hist_Salesiano_Paroquia
22563 [http-8088-1] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity br.salesianos.modelo.Hist_Salesiano_Paroquia on table Hist_Salesiano_Paroquia
22578 [http-8088-1] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: br.salesianos.modelo.Estado.cidade -> Cidade
22578 [http-8088-1] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: br.salesianos.modelo.Inspetoria.comunidade -> Comunidade
22672 [http-8088-1] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: br.salesianos.modelo.Inspetoria.familiasalesiana -> Familia_Salesiana
22672 [http-8088-1] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: br.salesianos.modelo.Comunidade.histComunidadeObra -> Hist_Comunidade_Obra
22672 [http-8088-1] INFO org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: br.salesianos.modelo.Obra.histComunidadeObra -> Hist_Comunidade_Obra
22672 [http-8088-1] INFO org.hibernate.cfg.AnnotationConfiguration - Hibernate Validator not found: ignoring
22766 [http-8088-1] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
22766 [http-8088-1] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
22766 [http-8088-1] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
22766 [http-8088-1] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/CurriculoSDB
22875 [http-8088-1] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=postgres, password=****}
22906 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - RDBMS: PostgreSQL, version: 9.0.0
22906 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 9.0devel JDBC3 (build 800)
22906 [http-8088-1] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.PostgreSQLDialect
22906 [http-8088-1] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
22906 [http-8088-1] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
22969 [http-8088-1] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
22969 [http-8088-1] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
22969 [http-8088-1] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
23016 [http-8088-1] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
Hibernate: 
    select
        this_.est_id as est1_631_0_,
        this_.est_nom as est2_631_0_,
        this_.est_sigla as est3_631_0_ 
    from
        Estado this_

alguem tem alguma ideia de como solucionar isso?

5 Respostas

J

De uma estudada no ciclo de vida do JSF que tu vai entender o pq da query ser chamada varias vezes. Apenas para adiantar, durante um ciclo inteiro do JSF, um metodo GET é chamado mais de uma vez, e como tu não está armazenando nem verificando se ja foi chamado, todo o codigo (incluindo a chamada ao banco) está sendo chamada mais de uma vez.

leonardoMachado

Acho interessante, vc ter uma propriadade da lista que vc precisa no seu managed bean, pois da forma que está implementado toda vez que vc chama getSuaLista() ele refaz a consulta de novo. Se a partir de uma ação (pesquisar, filtrar…) vc carregar a lista e no getSuaLista() vc devolver ela, certamente fica melhor. Faça o teste.

F

Quando vc fala para eu fazer uma pesquisa ou filtro, com qual elemento eu posso fazer ela, pois eu achei que o criteria ja fosse um tipo de pesquisa, não sei como posso fazer uma pesquisa sem utilizar o criteria, tentei utilizar hql para fazer uma pesquisa, mas o resultado foi o mesmo, o loop aconteceu

leonardoMachado

Então o criteria faz isso, porém como já foi citado o método getSuaLista() é invocado algumas vezes por causa do ciclo de vida do JSF…
É algo mais ou menos assim:

package br.salesianos.db;   
  
import br.salesianos.modelo.Estado;   
import java.util.ArrayList;   
import java.util.List;   
import javax.faces.bean.ManagedBean;   
import org.hibernate.Session;   
  
@ManagedBean   
public class seuManagedBean {   
  
    private List suaLista;
  
	public seuManagedBean() {
		filtrar();
	}
	
	public void filtrar() {
		Session sessao = CriadorDeSessao.getSession();       
        suaLista = sessao.createCriteria(Estado.class).list();
	}
	
    public List getSuaLista() {
		return suaLista;
    }   
  
    /**  
     * @param suaLista the suaLista to set  
     */   
    public void setSuaLista(List suaLista) {   
        this.suaLista = suaLista;   
    }  
}

E sempre que vc precisar refazer a lista, vc a partir da sua página (xhtml ou jsp) vc chama o método filtrar…

F

Ai leonardoMachado, to impressionado mesmo, realmente funcionou, mas tenho q ser sincero, pois realmente não entendi muito bem, eu dei uma olhada nos ciclos do JSF e vi como ele faz as coisas por tras dos panos, é um pouco complexo, mas não entendi porque o JSF conseguiu pular os ciclos do JSF e fazer somente uma vez a chamada do hibernate.

Outra coisa, eu não mudei nada na minha pagina xhtml, continuou tudo do mesmo jeito q tava antes, vc tinha dito que tinha que chamar o filtrar na pagina xhtml, porém o metodo filtrar é chamado a partir do construtor, nao tem jeito de chamar ele diretamente, fiquei um pouco confuso com isso tbm

E a ultima coisa, da maneira que está agora funciona, porém ele cria a listagem pra classe Estado devido a chamada do metodo filtrar no construtor(ele passa a classe Estado no createCriteria), porém pra criar listagens de outras classes(que tem várias na minha aplicação) so sei fazer criando outro ManagedBean, pois é a partir dele que é criado o construtor que chama o filtro especifico para gerar a listagem da classe que eu quero,
queria saber se é possivel criar a chamada pra todas as demais listas que eu possuo como “Cidade” no mesmo ManagedBean que eu uso pra gerar a lista dos Estados?

vlw

Criado 22 de março de 2011
Ultima resposta 23 de mar. de 2011
Respostas 5
Participantes 3