Java Reference
In-Depth Information
Getting results
When we receive the
YES
or
NO
value from the database, we need to translate it
into a boolean value of
true
or
false
. This is the exact opposite of what we just
did to set parameters. So why don't we start the same way? Let's build a method to
translate the string type to the boolean type, like this:
private Boolean yesNoToBoolean(String s) {
if (YES.equalsIgnoreCase(s)) {
return Boolean.TRUE;
} else if (NO.equalsIgnoreCase(s)) {
return Boolean.FALSE;
} else {
throw new IllegalArgumentException (
"Could not convert " + s +
" to a boolean value. " +
"Valid arguments are 'YES' and 'NO'.");
}
}
We can now use this method to translate the String results from the database into
the boolean values we need. We can do this by calling our new translation method
from the
getResult()
method of the
TypeHandlerCallback
. The
getResult()
method has only one parameter:
ResultGetter
.
ResultGetter
contains methods
for retrieving values of different types. In our case, we need to get a String value.
Here's the code for the
getResult()
implementation:
public Object getResult(ResultGetter getter)
throws SQLException {
return yesNoToBoolean(getter.getString());
}
In this case we're calling
getString()
on the
ResultGetter
to return the database
value as a String. We then pass the returned value to our convenient translation
method, which returns the
Boolean
value that we ultimately want to be set in the
enabled
property of our
User
class.
Dealing with nulls: what the heck is this valueOf() method for?
iBATIS
has a null value translation feature that allows you to work with nullable col-
umns in the database without requiring a nullable type in the object model. This is
especially valuable when you don't have full design control over the object model
or the database but you must map the two together. So for example, if you have an
int
typed property on your Java class, it will not accept a null value. If you must
map that property to a nullable column in the database, then you have to use a
constant to represent the null value. Sometimes this is called a “magic number,”
