开发者

Is there a way to avoid wasNull() method?

开发者 https://www.devze.com 2023-03-12 07:34 出处:网络
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

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开发者_Python百科("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.


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));


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消