somewhat daily mutterings

/Programming/Java Bug in Hibernate UserType Example

In Gavin King's excellent book Hibernate in Action, there lurks an insidious bug. If you follow his custom UserType implementation example on page 203, you're in for big trouble and lengthy debugging sessions. Here's the example

public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) 
        throws HibernateException, SQLException {

    if (resultSet.wasNull()) return null;    // <------- BUG!!

    BigDecimal value = resultSet.getBigDecimal(names[0]);
    return DataUtils.toPercentage(value);
}

The problem with the above code is that the wasNull() call is not preceded by a get*() call. In our particular circumstance, once wasNull() returned true (due to a null value in a given column), it kept returning true for every column that was mapped using the UserType. This, of course, resulted in the subsequent fields of this type being given null values, even if the column did not contain a null value.

Do I need to say that this is a very subtle bug that pops out in odd places, and is extremely difficult to find? I spent hours with log messages and the debugger. The right way to do it is as follows.

public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) 
        throws HibernateException, SQLException {

    String name = resultSet.getString(names[0]);  // <----- You GOTTA do this!
    if (resultSet.wasNull()) return null;

    BigDecimal value = resultSet.getBigDecimal(names[0]);
    return DataUtils.toPercentage(value);
    }

Posted: Fri Jan 28 10:53:52 -0800 2005

Thanks for visiting! Send comments to Mike Thomas.

Site 
Meter