Sachin
Sachin

Reputation: 18757

Is there a way to avoid wasNull() method?

I have a big ResultSet (getting from a JDBC query) of few thousand rows. Using each of these rows, I have to instantiate an Object, setting fields of it according to the fields of this result set. Now, as we all know, the getXXX() methods of this JDBC API return 0 if that particular column was null. So for each field of each row, I have to do a wasNull() before setting the value in my object, which looks pretty ugly and may be is not efficient as well. So, is there any other way by which I can avoid it?

Apart from JDBC, if there is some entirely different, standard, commonly used way, I am open to know about that as well.

Thanks!

EDIT 1

patientInput.setRaceCodeId(patients.getShort("race_code_id"));  
if(patients.wasNull())
    patientInput.setRaceCodeId(null);

patients is a ResultSet. patientInput is an object. This is the code which I am trying to avoid. I mean, everytime I do a getXXX(), and do a setXXX(), I have to check again that what I got from ResultSet was not null. If it was, then set that object field as null, as getXXX() returns 0 in that case.

Upvotes: 3

Views: 2309

Answers (2)

GordyD
GordyD

Reputation: 5103

Ok. I believe there are two possible approaches to 'tidying' up your code. However, this could come down to a difference of opinion as to what is tidy!

Solution 1 - replace getXXX() with getObject() which returns null e.g.

Short s = (Short)patients.getObject("race_code_id");
patientInput.setRaceCodeId(s); 

Solution 2 - write a generic wrapper method that retrieves nullable values

protected final <T> T getNullableValue(T returnType, String colName, ResultSet rs) throws SQLException {  
  Object colValue = rs.getObject(colName);  
  return (T) colValue;  
}

final static Integer INT = 0;
final static Short SHORT = 0;
.
.
.
patientInput.setRaceCodeId(getNullableValue(SHORT,"race_code_id",patients));

Upvotes: 3

Olaf
Olaf

Reputation: 6289

You don't have to do it to each field, only to fields that are numeric and, possibly, boolean, and are declared as nullable in your database. It happens not as frequently as you fear.

If you absolutely hate writing such code, you can try switching to an ORM library, for example, Hibernate.

Upvotes: 2

Related Questions