Thursday, February 17, 2011

JAXB, Equals and hashCode methods

I have no need to have a equals and hashCode methods on generated java class yet but I need it now.

It is really simple. You have to use a specific jaxb plugin (in case of Maven) and plugins for this plugin ;-)

- Maven2 plugin: org.jvnet.jaxb2.maven2:maven-jaxb2-plugin
- configuration: -XtoString, -Xequals, -XhashCode
- plugin for Maven2 plugin: org.jvnet.jaxb2_commons:jaxb2-basics

While java classes are being generated this plugin hooks at the process and add equals and hashCode methods. My pom definition:


<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.7.4</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<clearOutputDir>true</clearOutputDir>
<extension>true</extension>
<schemaDirectory>target/schemas</schemaDirectory>

</configuration>
</execution>
</executions>
<configuration>
<args>
<arg>-XtoString</arg>
<arg>-Xequals</arg>
<arg>-XhashCode</arg>
</args>
<plugins>
<plugin>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics</artifactId>
<version>${version.jaxb2-basics}</version>
</plugin>
</plugins>
</configuration>
</plugin>


That's it!

1 comment:

  1. Nice article but I believe its important to understand the consequences of not following this contract as well and for that its important to understand application of hashcode in collection classes e.g. How HashMap works in Java and how hashcode() of key is used to insert and retrieve object from hashMap.

    Javin

    ReplyDelete