JDBC Persistence
Now that you have a general foundation
for object persistence, you can use these classes to create a
JDBC-based persistence package. The generic library has set aside
implementations of the PersistenceSupport
and
Transaction
interfaces as the places where data
store-specific persistence operations should occur. To create a
database persistence library, you thus need to
create database-specific extensions of these two classes.
Here you get the chance to put your JDBC skills to use. I already
showed how a JDBCTransaction
class might implement
commit()
and rollback()
methods. JDBC support requires still more work. You need to create
JDBC Connection
instances used to talk to the
database. You also need to write the actual methods that talk to the
database. A getConnection( )
method in the JDBCTransaction
class takes care of
the first problem:
public Connection getConnection( ) throws SQLException {
if( connection == null ) {
Context ctx = new InitialContext( );
DataSource ds = (DataSource)ctx.lookup("jdbc/ora");
connection = ds.getConnection("borg", "pw");
connection.setAutoCommit(false);
}
return connection;
}
In this
code, I use the JDBC 2.0 Optional
Package method for connecting to a database. You may not have the
JDBC 2.0 Optional Package available to you, in which case you may
want to use the old-fashioned DriverManager
approach to making a Connection
. Either way, you definitely want a pooled connection. Without access to the JDBC 2.0 Optional Package, you have ...
Get Database Programming with JDBC & Java, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.