This page provides examples that show how DbUtils may be used.
DbUtils is a very small library of classes so it won't take long
to go through the javadocs for each class.
The core classes/interfaces in DbUtils are
QueryRunner
and
ResultSetHandler
.
You don't need to know about any other DbUtils classes to benefit from using the
library. The following example demonstrates how these classes are used together.
You could also perform the previous query using a java.sql.Connection
object
instead of a DataSource
. Notice that you are responsible for closing the
Connection
in this example.
In the examples above we implemented the ResultSetHandler
interface
to turn the first row of the ResultSet
into an Object[]. This is a
fairly generic implementation that can be reused across many projects.
In recognition of this DbUtils provides a set of ResultSetHandler
implementations in the
org.apache.commons.dbutils.handlers
package that perform common transformations into arrays, Maps, and JavaBeans.
There is a version of each implementation that converts just the first row and
another that converts all rows in the ResultSet
.
QueryRunner run = new QueryRunner(dataSource); // Use the BeanHandler implementation to convert the first // ResultSet row into a Person JavaBean. ResultSetHandler h = new BeanHandler(Person.class); // Execute the SQL statement with one replacement parameter and // return the results in a new Person object generated by the BeanHandler. Person p = (Person) run.query( "SELECT * FROM Person WHERE name=?", "John Doe", h);
Each of the provided ResultSetHandler
implementations accept a
RowProcessor
to do the actual conversion of rows into objects. By default the handlers
use the BasicRowProcessor
implementation but you can implement a custom version to plug in.
Probably the most common customization is to implement the toBean()
method to handle custom database datatype issues.
BasicRowProcessor
uses a BeanProcessor
to convert ResultSet
columns into JavaBean properties. You can
subclass and override processing steps to handle datatype mapping specific to
your application. The provided implementation delegates datatype conversion to
the JDBC driver.
BeanProcessor maps columns to bean properties as documented in the
BeanProcessor.toBean() javadoc.
Column names must match the bean's property names case insensitively.
For example, the firstname
column would be stored in the bean
by calling its setFirstName()
method. However, many database
column names include characters that either can't be used or are not typically
used in Java method names. You can do one of the following to map
these columns to bean properties:
select social_sec# as socialSecurityNumber from person