« Comparing coffee with gemstones | Main | Schiavo case was not about the "right to live" »

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

Comments (3)

Yep, I can read the examples now. Just wish I could understand them :-)

Ah, well... that's a different problem. :)

If you have questions about any particular example, feel free to ask.

Twice:

I was bitten by the same thing a few days ago.

Post a comment


About

This page contains a single entry from the blog posted on March 24, 2005 4:01 PM.

The previous post in this blog was Comparing coffee with gemstones.

The next post in this blog is Schiavo case was not about the "right to live".

Many more can be found on the main index page or by looking through the archives.

Creative Commons License
This weblog is licensed under a Creative Commons License.
Powered by
Movable Type 3.35