views:

108

answers:

2

When using JDBC and accessing primitive types via a result set, is there a more elegant way to deal with the null/0 than the following:

int myInt = rs.getInt(columnNumber)
if(rs.wasNull())?
{
 // Treat as null
} else
{
 // Treat as 0
}

I personally cringe whenever I see this sort of code. I fail to see why ResultSet was not defined to return the boxed integer types (except, perhaps, performance) or at least provide both. Bonus points if anyone can convince me that the current API design is great :)

My personal solution was to write a wrapper that returns an Integer (I care more about elegance of client code than performance), but I'm wondering if I'm missing a better way to do this.

Just to clarify, what bothers me about this code is not the length, but the fact that a it creates a state dependency between subsequent calls, and what appears like a simple getter actually has a side effect within the same row.

+6  A: 

The JDBC API was designed for performance. Remember that it dates back to Java 1.1, when a large turnover of objects was a JVM killer (it wasn't until the Hotspot JVMs in Java 1.2+ that you could relax this kind of limitation). Using boxed types would have ruined the performance of high volume applications at the time.

Now, it can't be changed because of backwards compatibility. So no, it's not ideal any more, but it's a pretty minor thing to workaround.

If you want to avoid the type of code you mentioned, you can always use getObject() instead of getInt(), which will return an object of one of the subtypes of java.lang.Number, probably Integer or BigInteger, depending on the specific SQL type.

skaffman
It's a pity getObject() hasn't been generified like Spring's RowMapper, JdbcTemplate and the like. It's only syntactic sugar, but makes the code look much nicer without the casts.
mdma
+1  A: 

@skaffman nailed it down.

In a nutshell, if you have to handle with "primitive" fields which are allowed to be null, then you should use the wrapper object in the Java side. I.e. Integer instead of int and so on. You can then use the following idiom to gather possibly-null primitives from DB:

Integer age = rs.getObject("age") != null ? rs.getInt("age") : null;

It has certainly no performance cost since the data is already in Java's memory once next() is called.

BalusC
Aren't you paying a double string lookup here?
Uri
The data in question is already in the memory. It are just accessors.
BalusC