Preencher um ComboBox RichFaces com dados do Banco

25/11/2009

Bom dia ,

Estou tentando popular um comboBox do RichFaces , mas estou tendo problemas , a query é realizada normalmente mas da um erro de cast.

veja o codigo abaixo :

public List<SelectItem> atualizaComboCidade() {

        itensCidades = new ArrayList<SelectItem>();
        ceps = (List<Cep>) todosResultItensCidades();
       
        for (Cep e : ceps) {
            itensCidades.add(new SelectItem(new String(e.getCidade())));
        }

        setCi(true);
        return itensCidades;

    }

    private List<?> todosResultItensCidades() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("uf", uf);

        return cepDao.listPesqParam(consultaCidades(), params);

    }

    private String consultaCidades() {
        String query = "SELECT " +
                " DISTINCT(c.cidade) FROM Cep c " +
                " WHERE c.uf = :uf";

        return query;
    }


  Trecho do codigo Xhtml


<h:outputText  styleClass="rich-label" value="Selecione o Estado" />
                            <rich:comboBox  size="2" label="UF" defaultLabel="UF" id="uf" required="true" value="#{rotaController.uf}" >
                                <f:selectItem itemValue="AC"/>
                                <f:selectItem itemValue="AL"/>
                                <f:selectItem itemValue="AM"/>
                                <f:selectItem itemValue="AP"/>
                                <f:selectItem itemValue="BA"/>
                                <f:selectItem itemValue="CE"/>
                                <f:selectItem itemValue="DF"/>
                                <f:selectItem itemValue="ES"/>
                                <f:selectItem itemValue="GO"/>
                                <f:selectItem itemValue="MA"/>
                                <f:selectItem itemValue="MG"/>
                                <f:selectItem itemValue="MS"/>
                                <f:selectItem itemValue="MT"/>
                                <f:selectItem itemValue="PA"/>
                                <f:selectItem itemValue="PB"/>
                                <f:selectItem itemValue="PE"/>
                                <f:selectItem itemValue="PI"/>
                                <f:selectItem itemValue="PR"/>
                                <f:selectItem itemValue="RJ"/>
                                <f:selectItem itemValue="RN"/>
                                <f:selectItem itemValue="RO"/>
                                <f:selectItem itemValue="RR"/>
                                <f:selectItem itemValue="RS"/>
                                <f:selectItem itemValue="SC"/>
                                <f:selectItem itemValue="SE"/>
                                <f:selectItem itemValue="SP"/>
                                <f:selectItem itemValue="TO"/>
                                <f:validateLength minimum="2" maximum="2"  />
                               <a4j:support event="onchange" action="#{rotaController.atualizaComboCidade}" reRender="comboCidade"/>
                            </rich:comboBox>

                            <a4j:commandButton value="update" reRender="comboCidade"/>
                            <h:outputText  styleClass="rich-label" id="lbcidade"  rendered="#{rotaController.ci == true}"   value="Selecione a Cidade:" />
                            <rich:comboBox  id="comboCidade" rendered="#{rotaController.ci == true}"  value="#{rotaController.cidade}"
                                            defaultLabel="Selecione a Cidade..." required="true" >
                                <f:selectItems value="#{rotaController.itensCidades}"/>
                                <a4j:support event="onchange"
                                             ajaxSingle="true" reRender="bairro" />
                            </rich:comboBox>


Victor Lima

Respostas

25/11/2009

Victor Lima

Faltou o erro :

Hibernate:
    select
        distinct cep0_.cidade as col_0_0_
    from
        public.cep cep0_
    where
        cep0_.uf=?
12:28:43,244 DEBUG StringType:133 - binding 'RJ' to parameter: 1
12:28:43,914 DEBUG StringType:172 - returning 'Barra do Piraí' as column: col_0_0_
12:28:43,914 DEBUG StringType:172 - returning 'Barra Mansa' as column: col_0_0_
12:28:43,915 DEBUG StringType:172 - returning 'Belford Roxo' as column: col_0_0_
12:28:43,915 DEBUG StringType:172 - returning 'Cabo Frio' as column: col_0_0_
12:28:43,916 DEBUG StringType:172 - returning 'Campos dos Goytacazes' as column: col_0_0_
12:28:43,916 DEBUG StringType:172 - returning 'Duque de Caxias' as column: col_0_0_
12:28:43,917 DEBUG StringType:172 - returning 'Itaguaí' as column: col_0_0_
12:28:43,917 DEBUG StringType:172 - returning 'Japeri' as column: col_0_0_
12:28:43,918 DEBUG StringType:172 - returning 'Macaé' as column: col_0_0_
12:28:43,918 DEBUG StringType:172 - returning 'Mesquita' as column: col_0_0_
12:28:43,919 DEBUG StringType:172 - returning 'Nilópolis' as column: col_0_0_
12:28:43,919 DEBUG StringType:172 - returning 'Niterói' as column: col_0_0_
12:28:43,920 DEBUG StringType:172 - returning 'Nova Friburgo' as column: col_0_0_
12:28:43,920 DEBUG StringType:172 - returning 'Nova Iguaçu' as column: col_0_0_
12:28:43,920 DEBUG StringType:172 - returning 'Petrópolis' as column: col_0_0_
12:28:43,921 DEBUG StringType:172 - returning 'Quatis' as column: col_0_0_
12:28:43,921 DEBUG StringType:172 - returning 'Queimados' as column: col_0_0_
12:28:43,922 DEBUG StringType:172 - returning 'Resende' as column: col_0_0_
12:28:43,922 DEBUG StringType:172 - returning 'Rio de Janeiro' as column: col_0_0_
12:28:43,923 DEBUG StringType:172 - returning 'São Gonçalo' as column: col_0_0_
12:28:43,923 DEBUG StringType:172 - returning 'São João de Meriti' as column: col_0_0_
12:28:43,924 DEBUG StringType:172 - returning 'Teresópolis' as column: col_0_0_
12:28:43,924 DEBUG StringType:172 - returning 'Três Rios' as column: col_0_0_
12:28:43,925 DEBUG StringType:172 - returning 'Volta Redonda' as column: col_0_0_
12:28:43,933 ERROR BaseXMLFilter:199 - Exception in the filter chain
javax.servlet.ServletException: #{rotaController.atualizaComboCidade}: java.lang.ClassCastException: java.lang.String cannot be cast to br.com.webtracking.entity.Cep
Responder Citar

25/11/2009

Dyego Carmo

Sua lista não contem classes Cep , contem apenas strings com o valor do Cep

na linha:

for (Cep e : ceps) {
            itensCidades.add(new SelectItem(new String(e.getCidade())));
        }

troque para:

for (Object e : ceps) {
            System.out.println("Veja a minha classe "+e.getClass()+" e meu valor "+e.toString());
        }


veja no console... vai imprimir as classes e os valores.



Responder Citar

25/11/2009

Victor Lima



 Boa Tarde,


 Mesmo erro javax.servlet.ServletException: #{rotaController.atualizaComboCidade}: java.lang.ClassCastException: java.lang.String cannot be cast to br.com.webtracking.entity.Cep


 Eu tenho a classe CEP sim  veja:

 /**
 *
 * @author victor
 */
@Entity
@Table(name = "public.cep")
public class Cep implements Serializable {

    private static final long serialVersionUID = 1L;
   
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "idcep")
    private Integer idCep;

    @Column(name = "cep")
    private String cep;

    @Column(name = "logradouro")
    private String logradouro;

    @Column(name = "bairro")
    private String bairro;

    @Column(name = "cidade")
    private String cidade;

    @Column(name = "uf")
    private String uf;

    @Column(name = "tipo")
    private String tipoLogradouro;

    @Column
    private Boolean isrisco;

    @Column
    private Boolean isfaixa;

    @Column
    private Integer num_ini;


    @Column
    private Integer num_fim;




    @OneToMany(mappedBy = "cep", fetch = FetchType.LAZY)
    private Set<Pedido> pedidos;


    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="idrota",referencedColumnName="id")
    private Rota codrota;

   .....  g e s
Responder Citar

25/11/2009

Victor Lima

 Foi declarado ,


 private List<Cep> ceps;

 

obrigado

Victor
Responder Citar

25/11/2009

Victor Lima



 Assim tambem nao vai.


public List<SelectItem> atualizaComboCidade() {

        itensCidades = new ArrayList<SelectItem>();

         Iterator iterator = todosResultItensCidades().iterator();
            while (iterator.hasNext()) {
                Object[] o = (Object[]) iterator.next(); // restante do loop
                itensCidades.add(new SelectItem(o.toString()));

            }
        setCi(true);
        return itensCidades;

    }


Erro

15:02:02,198 ERROR BaseXMLFilter:199 - Exception in the filter chain
javax.servlet.ServletException: #{rotaController.atualizaComboCidade}: java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;
Responder Citar

25/11/2009

Victor Lima

Agora que parei para entender que vc falou que nao tinha uma classe,

 funcionou,  Obrigado.

Segue codigo para comunidade.



  public List<SelectItem> atualizaComboCidade() {

        itensCidades = new ArrayList<SelectItem>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("uf", getUf());
        ceps = (Iterable<Object>) todosResultItensCidades();
        for (Object e : ceps) {
            System.out.println("Veja a minha classe "+e.getClass()+" e meu valor "+e.toString());
            itensCidades.add( new SelectItem(e.toString()));// label,value
        }

        setCi(true);
        return itensCidades;

    }

Responder Citar