Tuesday, December 9, 2008

Maven generating JAXB with the Fluent API

I thought this was interesting and there wasn't a lot of information on this online. It's using the Maven JAXB plugin to generate JAXB classes with the Fluent API. All the regular methods for getting and setting values are available, but there is also an API to chain together setting and creating classes. Thanks to Steve Berman for the Maven config.

Standard API

PersonResponse personList = new PersonResponse();

Person person = new Person();
person.setId(ID);
person.setFirstName(FIRST_NAME);
person.setLastName(LAST_NAME);

Person person2 = new Person();
person2.setId(SECOND_ID);
person2.setFirstName(SECOND_FIRST_NAME);
person2.setLastName(SECOND_LAST_NAME);

personList.getPerson().add(person);
personList.getPerson().add(person2);


Fluent API

PersonResponse personList = new PersonResponse().withPerson(
    new Person().withId(ID).withFirstName(FIRST_NAME).withLastName(LAST_NAME),
    new Person().withId(SECOND_ID).withFirstName(SECOND_FIRST_NAME).withLastName(SECOND_LAST_NAME));


Inside the build element's plugins section, this can be added to generate JAXB beans with the Fluent API.

<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <configuration>
        <extension>true</extension>
        <args>
            <arg>-Xfluent-api</arg>
        </args>
        <schemaDirectory>src/main/resources</schemaDirectory>
        <plugins>
            <plugin>
                <groupId>net.java.dev.jaxb2-commons</groupId>
                <artifactId>jaxb-fluent-api</artifactId>
                <version>2.1.8</version>
            </plugin>
        </plugins>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

<repositories>
    <repository>
        <id>maven2-repository.dev.java.net</id>
        <name>Java.net Maven 2 Repository</name>
        <url>http://download.java.net/maven/2</url>
    </repository>
</repositories>