jDBI provides a convenience interface for SQL operations in Java. It is not intended as an abstraction layer, but rather a library which makes the common things easy and the hard things possible, to paraphrase Larry Wall.
The primary entry point for using jDBI is the DBI class. This
is used to create Handle instances, each of which
represents a connection to the RDBMS. A Handle wraps a JDBC Connection
instance, and makes use of
that same Connection for all of its operations.
Generally, you will explicitely create statements, queries, and batch operations for working with data in the database. Seperate objects are used to represent these things, and they are designed to be used in a somewhat literate-programming style. Here is an example:
DBI dbi = new DBI("jdbc:derby:testing");
Handle handle = dbi.open();
Query<Something> query = handle.createQuery("select * from something where name like :name")
.bind("name", "Eri%")
.map(Something.class);
List<Something> rs = query.list();
handle.close();
This example just exercises the basics of jDBI. We'll explore the details in the remainder of this documentation.
The two most common ways are to pass in the JDBC connection information, the url, username, and password. In this
case a new connection will be opened using the JDBC DriverManager
for each Handle
. An
alternate, and more efficient means, is to pass a DataSource
to the DBI
constructor.
This allows for connection pooling in the datasource, which is generally a good thing. If neither of these
approaches work well, it is possible to provide your own ConnectionFactory
implementation which
will be used to obtain JDBC connections.
A special case exists for using jDBI in Spring where you want to use Spring's transaction management system. This case is described more fully in the Spring Integration documentation.
The Handle
basically is a connection to the database. A handle wraps a single JDBC connection
which it uses for all of its work.
The handle is used, primarily, to create various kinds of statements: queries, statements, batches, prepared batches, etc. In addition to these, it has a couple convenience methods for the most commons cases -- simple statements and queries with positional parameters. The javadocs for the Handle explain these.
The general idiom for working with the database is to create a statement object from the handle. This will usually be a SQLStatement or a Query. When you create the statement object you can then configure exactly how you want it to work, then call execute(), list(), iterate(), or first() as appropriate.
A handle is not thread-safe, though it can be used in multithreaded code with external synchronization.