How to populate options of h:selectOneMenu from database?

前端 未结 5 1893
情话喂你
情话喂你 2020-11-21 05:03

I am creating a web application, where you have to read a list of objects / entities from a DB and populate it in a JSF . I am unable to

5条回答
  •  自闭症患者
    2020-11-21 05:24

    I'm doing it like this:

    1. Models are ViewScoped

    2. converter:

      @Named
      @ViewScoped
      public class ViewScopedFacesConverter implements Converter, Serializable
      {
              private static final long serialVersionUID = 1L;
              private Map converterMap;
      
              @PostConstruct
              void postConstruct(){
                  converterMap = new HashMap<>();
              }
      
              @Override
              public String getAsString(FacesContext context, UIComponent component, Object object) {
                  String selectItemValue = String.valueOf( object.hashCode() ); 
                  converterMap.put( selectItemValue, object );
                  return selectItemValue;
              }
      
              @Override
              public Object getAsObject(FacesContext context, UIComponent component, String selectItemValue){
                  return converterMap.get(selectItemValue);
              }
      }
      

    and bind to component with:

     
    

    If you will use entity id rather than hashCode you can hit a collision- if you have few lists on one page for different entities (classes) with the same id

提交回复
热议问题