Does JAXB support xsd:restriction?
The JAXB (JSR-222) specification does not cover generating fail fast logic into the domain model. A common practice now is to express validation rules in the form of annotations (or XML) and run validation on them. Bean Validation (JSR-303) standardizes this and is available in any Java EE 6 implementation.
XJC Extensions
I have not tried the following extension myself but it appears as though it will generate Bean Validation (JSR-303) annotations onto the domain model representation validation rules from the XML schema. As XJC is very extensible there may be other plug-ins available as well.
- https://github.com/krasa/krasa-jaxb-tools
The suggested way to perform this validation in JAXB is switching on schema validation on the marshaller resp. unmarshaller:
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(...);
ValidationEventHandler valHandler = new ValidationEventHandler() {
public boolean handleEvent(ValidationEvent event) {
...
}
};
marshaller.setSchema(schema);
marshaller.setEventHandler(valHandler);
You can try JAXB-Facets. Quick snippet:
class MyClass {
@MinOccurs(1) @MaxOccurs(10)
@Facets(minInclusive=-100, maxInclusive=100)
public List<Integer> value;
@Facets(pattern="[a-z][a-z0-9]{0,4}")
public String name;
}