Share this page to your:
Mastodon

I kept the previous post short because I know I never read long blog posts. So here is some more about Madura Objects. Recall that we generate Java using JAXB/XJC and that is injected with plugins. Our resulting classes are just beans… with some extra stuff.

Now, let’s assume the XSD file you fed into XJC defined an object called Customer which has a field called name. The definition for name looks like this:

<element name="name">
    <simpletype>
        <restriction base="string">
            <maxlength value="30"/>
            <pattern value="a*b"/>
        </restriction>
    </simpletype>
</element>

This is just ordinary XSD stuff and it says that this field must be no longer then 30 characters and specifies a regex pattern the contents must conform to.

Okay, now we build a little code….

Customer customer = new Customer();
validationSession.bind(customer);
boolean exceptionFound = false;
try {
    customer.setName("ttt");
} catch (ValidationException e) {
    exceptionFound = true;
}
assertTrue(exceptionFound);

All I did here was instantiate the Customer object (Customer.java was generated by XJC) and then bind it to the validationSession I’d created earlier. Then I attempted to set a value in the name. But the value does not pass the regex expression so I get an exception. The bind call will automatically bind to every object attached to Customer, including ones I add after the bind. So we don’t need to bind very often. After the bind there is actually no API to remember. Just use the objects normally and handle exceptions.

If you instantiate an object, unpack it from XML using JAXB or fetch it from a database using Hibernate (all of which are easy to do with these generated objects) then you have to bind it. If you fetch from Hibernate make sure you don’t use a lazy fetch because then the bind won’t find the attached objects.

If you don’t bind then the objects behave like normal beans, and this is sometimes just what you want.

Next time I’ll blog about metadata.

Previous Post Next Post