Over the weekend I created an advanced Spring Roo add-on to provide support for creation of compareTo method. This add-on is on similar lines of Spring Roo own equals add-on which provide implementation of equals and hashcode methods. The add-on is released and available for community to use. The add-on is listed in Spring Roo repository XML http://spring-roo-repository.springsource.org/roobot/roobot.xml . It is built using Spring Roo latest version 1.2.0.RC1. This post will talk about how to install and use the add-on.
Installing the compareTo add-on
Open the operating system command line and type roo. In case you don’t have Spring Roo setup please refer to my IBM DeveloperWork article on Spring Roo. After the roo shell initiates type the following command to install the add-on.
addon install bundle --bundleSymbolicName org.xebia.roo.addon.compareto
If you don’t have automatic pgp trust enable you will see a message on Roo shell saying that you first have to trust my pgp key before you can install the add-on. To trust the key type the following Roo command.
pgp trust --keyId 0x9B68220C
Once it is enable re-run the addon install command and add-on should get installed. To verify that add-on is installed type the osgi ps command and you should compareto add-on listed at the bottom of the command output.
[ 78] [Active ] [ 1] spring-dw-roo-compareto-addon (0.1.1.BUILD)
This add-on exposes two commands compareto setup and compareto and these commands are enabled after you have created entity. This is because before you have created any entity it does not make sense to have compareTo method.
Using the compareTo add-on
Lets first create a simple bookshop application. Type the following command which will create the project, setup database and create a simple book entity.
project --topLevelPackage com.xebia.bookshop --projectName bookshop jpa setup --database HYPERSONIC_IN_MEMORY --provider HIBERNATE entity jpa --class ~.domain.Book --testAutomatically field string --fieldName title --notNull field string --fieldName author --notNull field number --type double --fieldName price --notNull
After you have ran the commands above you can now create compareTo method for book entity.To create the compareTo method type the following commands.
compareto setup compareto add --type ~.domain.Book
The first command will add the required dependencies and second will create the Book_Roo_Compareto.aj ITD which contains the compareTo method.
If you want to exclude some fields in compareTo method you should specify i.e. if you don’t want author and price field to be used in compareTo method you can specify them in excludeFields attribute as shown below.
compareto add --type ~.domain.Book --excludeFields "author price"
Use this add-on and share feedback.