How can I generate Java objects with Bean Validation annotations from an XSD? How can I generate Java objects with Bean Validation annotations from an XSD? xml xml

How can I generate Java objects with Bean Validation annotations from an XSD?


You can use the javax.xml.valdation APIs to validation a domain model mapped with JAXB against an XML schema. An advantage of this approach is that you use the same validation rules (defined in the XML schema) for both of your use cases:

import java.io.File;import javax.xml.XMLConstants;import javax.xml.bind.JAXBContext;import javax.xml.bind.util.JAXBSource;import javax.xml.validation.*;public class Demo {    public static void main(String[] args) throws Exception {        Customer customer = new Customer();        customer.setName("Jane Doe");        customer.getPhoneNumbers().add(new PhoneNumber());        customer.getPhoneNumbers().add(new PhoneNumber());        customer.getPhoneNumbers().add(new PhoneNumber());        JAXBContext jc = JAXBContext.newInstance(Customer.class);        JAXBSource source = new JAXBSource(jc, customer);        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);        Schema schema = sf.newSchema(new File("customer.xsd"));        Validator validator = schema.newValidator();        validator.setErrorHandler(new MyErrorHandler());        validator.validate(source);    }}

Full Example


The best answer I know till now is to use the Annotate Plugin to add JSR 303 annotations.


You can generate Bean Validation annotations from xsd using this plugin https://github.com/krasa/krasa-jaxb-tools