Arguments against a universal JSF object converter with a static value of WeakHashMap

I want to avoid the boiler plate code for creating a SelectItems list to display my / dtos objects between the view and the model, so I used this fragment of a generic converter object:

@FacesConverter(value = "objectConverter") public class ObjectConverter implements Converter { private static Map<Object, String> entities = new WeakHashMap<Object, String>(); @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<Object, String> entry : entities.entrySet()) { if (entry.getValue().equals(uuid)) { return entry.getKey(); } } return null; } } 

Already there are answers to similiar questions, but I want a vanilla solution (without * faces). The following points still leave me uncertain about the quality of my fragment:

  • If it was that simple, why is there no built-in object converter in JSF ?
  • Why are so many people still using SelectItems ? Isn't there more flexibility using a common approach? For instance. # {dto.label} can be quickly changed to # {dto.otherLabel}.
  • Given that a region is simply a mapping between a view and a model, is there any significant drawback to the general approach?
+5
source share
1 answer

This approach is hacked, and memory is inefficient.

This is β€œgood” in a small application, but definitely not in a large application with tens or hundreds of thousands of potential objects that can be referenced in f:selectItems . Moreover, such a large application usually has a common cache of second-level objects. WeakHashMap then becomes useless and acts only when the object is physically deleted from the underlying data store (and, therefore, also from the cache of the second-level entity).

This is certainly a "fun" factor, but I would not recommend using it in "heavy production."

If you do not want to use an existing solution from the utility library, for example OmniFaces SelectItemsConverter , as you have already found that it is basically completely stateless and does not use any DAO / Service call, then your best choice is to abstract all your entities using a common base interface / class and instead intercept the converter. This still requires a DAO / Service call. This is described in detail in this Q&A: Implementing Transformers for Objects with Java Generics .

+6
source

All Articles