I have written a JAXB mapping that stored a sublist inside a root element in a LinkedHashMap<String, Object> instead of a Collection<Object> maintained through a specific XmlJavaTypeAdapter. Hereunder a sample:
@XmlRootElement
public class Parent {
@XmlJavaTypeAdapter(ListToMapAdapter.class)
@XmlElement
private LinkedHashMap<String, Child> children;
...
}
The key is built from the attributes of the child tag (e.g. <child id="key"> give a Map.Entry<String, Child> like {key => child}.
One of my coworker says its bad designed, and that this Map should be in the object in charge of unmarshalling the XML. I’m not agree with him. Here are some pros and cons on such an approach. Which design do you think is the best? And which pros and cons did you see to complete the debate?
Goal of this design:
- the
Mapgive the ability to search efficiently children with a criteria (the key in my sample) instead of search by iteration on a Collecion.
Pros:
- responsability for searching and filtering the sublist is at the nearest of the object and the parent object is responsible of retrieving and filtering its child,
- the building of the
Mapis automatically made by JAXB when unmarshalling: elegant, efficient, and preserve from building theMapwith a post process of the list after umarshalling (iteration), - the same object in different readers has still the ability of filtering its children,
- subjective, it’s really a pretty way of doing that :),
- if
@XmlJavaTypeAdapterexists, it’s partly for this (numerous samples of this on the Web).
Cons (some are from my coworker):
- JAXB limitation constraints to code to a concrete implementation instead of an interface: could not declare
Map<String, Child>in my sample (not instantiable by JAXB while unmarshalling), - maybe (and its the argument of my coworker), its not the role of a mapping object (simple POJO according to him) to have such a behavior,
@XmlJavaTypeAdapteraims only at converting simple object to specific types:xs:dateto Joda timeCalendarfor instance.
Thanks in advance for your 2 cents.
I always recommend that people design the best model possible for their application. Then let JAXB handle the difficulty of mapping it to XML. In this case if it makes sense for parent to have a Map of children then by all means model it this way. JAXB does have some support for Map, but with the XML representation you describe you will need to use an XmlAdapter. For more information see:
All of the Pros seem reasonable. None of the cons are valid:
If you want to eliminate the wrapper element, then you can use the @XmlPath extension in the MOXy JAXB implementation. The Foo class from my blog article would be modified slightly:
For more information see: