Java Reference
In-Depth Information
Listing 8.4. Adding creation and population of the
Product
table to the DAO
A phrase often used when describing Java is that the essence is buried in ceremony. JDBC
code is probably the worst offender in the whole API. The “essence” here is to create the
table and add a few rows. The “ceremony” is all the boilerplate surrounding it. As the list-
ing shows,
try
/
catch
blocks are needed because virtually everything in JDBC throws a
checked
SQLException
. In addition, because it's absolutely necessary to close the data-
base connection whether an exception is thrown or not, the connection must be closed in
a
finally
block. To make matters even uglier, the
close
method itself also throws an
SQLException
, so it, too, must be wrapped in a
try
/
catch
block, and of course the
only way to avoid a potential
NullPointerException
is to verify that the connection
and statement references are not null when they're closed.
This boilerplate is repeated inevery method inthe DAO.Forexample, the following listing
shows the implementation of the
findProductById
method.