Java Reference
In-Depth Information
Setting parameters
When we send a value to the database, it has to be YES or NO . In this case, null is
not valid. From the Java class, we're going to get a strongly typed boolean value of
true or false . So we need to translate true into a YES value and false into a NO
value. To do that, we could use a simple method like this:
private String booleanToYesNo(Boolean b) {
if (b == null) {
throw new IllegalArgumentException (
"Could not convert null to a boolean value. " +
"Valid arguments are 'true' and 'false'.");
} else if (b.booleanValue()) {
return YES;
} else {
return NO;
}
}
We can now use this method to translate parameter values before we set them. Set-
ting a parameter is easy. The setParameter() method of the TypeHandlerCallback
interface takes two parameters. The first, ParameterSetter , gives you access to a
number of setter methods, each of which works for a different data type. For
example, there is a setString() method, a setInt() method, and a setDate()
method. There are too many to list here completely, but rest assured that almost
any Java data type you're familiar with will probably have an associated set
method. In our case, the data type in the database table is a VARCHAR , so we'll use
the setString() method of the ParameterSetter .
The second parameter is the value we're passing to the database that needs to
be translated. In our case, we will be receiving the boolean value from the enabled
property from our User class. Here's the code for our setParameter() method
that uses our convenient booleanToYesNo() method that we wrote earlier:
public void setParameter(
ParameterSetter setter, Object parameter
) throws SQLException {
setter.setString(booleanToYesNo((Boolean) parameter));
}
The body of the method simply uses the ParameterSetter to set the string value
translated by our conversion method. We have to cast the incoming parameter to
Boolean , as the TypeHandlerCallback is an interface that can support any type.
That was simple, was it not? As you'll see in the next section, attaining results is
just as easy.
Search WWH ::




Custom Search