ibatis-user-java mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Benjamin Klatt" <benja...@bar54.de>
Subject iBator EqualsHashCodePlugin: NullPointerExceptions in equal method
Date Wed, 25 Mar 2009 11:32:12 GMT
Hey all,

we found an issue about the equal method.
Imagine you have a data object

---------
|Product|
---------
|id     |
|name   |
|desc   |
---------

And generate the java classes as well as the equal methods (id = Integer,
name&desc = String).

The Code

    Product p1 = new Product();
    p1.setId(1);
    p1.setName("p1");
    Product p2 = new Product();
    p2.setId(1);
    assertFalse("same id but diff names should return false",p1.equals(p2));

will result in a NullPointerException.
This results from the Boolean expression in the equal method. 
The combination of

return nullCheckAttribute1 ? nullCheckObject1 : equalAttribute1
	&& nullCheckAttribute2 ? nullCheckObject2 : equalAttribute2
	&& nullCheckAttribute3 ? nullCheckObject3 : equalAttribute3 ...

what happens:

nullCheckAttribute1 = false -> equalAttribute1
equalAttribute1 = true && nullCheckAttribute2 = false -> equalAttribute2
equalAttribute2 = false && nullCheckAttribute3 == false -> equalAttribute3

equalAttribute3 will result in the NullPointerException because in the
example this means
this.getDesc().equals(other.getDesc()
and this.getDesc() already returns null.

So to fix this issue parenthesis should be added in the following way:

return nullCheckAttribute1 ? nullCheckObject1 : equalAttribute1
	&& (nullCheckAttribute2 ? nullCheckObject2 : equalAttribute2
	&& (nullCheckAttribute3 ? nullCheckObject3 : equalAttribute3 ...))

The required code change in the plugin is:

        boolean first = true;
        int numberOfParenthesis = 0; //new counter for parenthesis
        Iterator<IntrospectedColumn> iter = introspectedColumns.iterator();
        while (iter.hasNext()) {
            IntrospectedColumn introspectedColumn = iter.next();
...
            if (!iter.hasNext()) {
            	for (int i = 0; i < numberOfParenthesis; i++) {
            		sb.append(')'); // append closing parenthesis
				}
                sb.append(';');
            }

I am sorry to posting this on the users mailing list instead of fixing the
code directly, but I don't have access to the repository.

@Jeff: It would be nice to see this integrated in the next version and to
throw away out adopted plugin ;)


All the best
Benjamin



----------------------
Benjamin Klatt

Mob.: +49 (0)179 - 979 55 46
Tel.: +49 (0)721 - 208 84 06

Kentuckyallee. 88
76149 Karlsruhe
Germany

Bahnhofstr. 21
37445 Walkenried
Germany  


Mime
View raw message