Remember to read the errata!

I’d introduced a Hibernate user type into the code base a few days ago. I’d based it on an example in the (more or less) wonderful book Hibernate in Action Naturally, however, I’d copied the example with a bug in it!


FWIW, the example is listing 6.1, on page 204. The code in question reads:

public Object nullSafeGet(ResultSet resultSet, String names, Object owner) throws HibernateException, SQLException {
  if (resultSet.wasNull()) return null;
  BigDecimal valueInUSD = resultSet.getBigDecimal(names[0]);
  return new MonetaryAmount(valueInUSD, Currency.getInstance("USD"));
}

The problem is that the first and second lines of the method are the wrong way around. ResultSet.wasNull(), btw, returns true if the last value extracted from the result set is null. As written, this will fail randomly if the previous column had contained null – hardly what’s desired. (It could also fail if the column intended is null, but that’s probably not as odd to try and diagnose) The reason to use ResultSet.wasNull(), instead of just looking at the returned value, is that the JDBC drive may not actually give you a null! For example, if you’re trying to get back a primitive (say, using ResultSet.getDouble(), instead of getBigDecimal()), you’re not going to get a null back, are you?

You can see this errata notice, and some more, at http://forum.hibernate.org/viewtopic.php?t=935347

3 thoughts on “Remember to read the errata!

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s