p:autocomplete for a global Entity Converter

前端 未结 2 834
死守一世寂寞
死守一世寂寞 2020-12-12 05:56

I want to build a p:autocomplete for searching different objects from a entities. Like customer, article....

The searching works well and the entities will appear.

2条回答
  •  时光说笑
    2020-12-12 06:11

    For AutoComplete try this generic converter

    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.UUID;
    import java.util.WeakHashMap;
    
    import javax.faces.component.UIComponent;
    import javax.faces.context.FacesContext;
    import javax.faces.convert.Converter;
    import javax.faces.convert.FacesConverter;
    
    @FacesConverter(value = "entityConverter")
    public class EntityConverter implements Converter {
    
        private static Map entities = new WeakHashMap();
    
        @Override
        public String getAsString(FacesContext context, UIComponent component, Object entity) {
            synchronized (entities) {
                if (!entities.containsKey(entity)) {
                    String uuid = UUID.randomUUID().toString();
                    entities.put(entity, uuid);
                    return uuid;
                } else {
                    return entities.get(entity);
                }
            }
        }
    
        @Override
        public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
            for (Entry entry : entities.entrySet()) {
                if (entry.getValue().equals(uuid)) {
                    return entry.getKey();
                }
            }
            return null;
        }
    
    }
    

提交回复
热议问题