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

Author: Robert Watkins

My name is Robert Watkins. I am a software developer and have been for over 20 years now. I currently work for people, but my opinions here are in no way endorsed by them (which is cool; their opinions aren’t endorsed by me either). My main professional interests are in Java development, using Agile methods, with a historical focus on building web based applications. I’m also a Mac-fan and love my iPhone, which I’m currently learning how to code for. I live and work in Brisbane, Australia, but I grew up in the Northern Territory, and still find Brisbane too cold (after 22 years here). I’m married, with two children and one cat. My politics are socialist in tendency, my religious affiliation is atheist (aka “none of the above”), my attitude is condescending and my moral standing is lying down.

3 thoughts on “Remember to read the errata!”

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: