O'Reilly logo

Database Programming with JDBC & Java, Second Edition by George Reese

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required