Sun GlassFish Mobility Platform 1.1 Developer's Guide for Enterprise Connectors

Extending the InsertCommand, UpdateCommand, and DeleteCommand Classes

The InsertCommand, UpdateCommand, and DeleteCommand classes all extend the Command class.

For details on these classes, see The InsertCommand Class, The UpdateCommand Class, The DeleteCommand Class, and The Command Class.

For the MusicDB example, the implementations of the three classes are almost identical. The source files for the implementations are MusicAlbumInsertCommand.java, MusicAlbumUpdateCommand.java, and MusicAlbumDeleteCommand.java.

Each source file begins by importing Java SE packages and the required ECBO API classes. It then begins by setting up a logger and declaring two objects that are used by the constructor method and the execute method. For example, MusicAlbumInsertCommand.java begins as follows:

public class MusicAlbumInsertCommand extends InsertCommand<MusicAlbum> {

    static final Logger logger = BusinessObjectProvider.getLogger();
    
    private String sqlStatement;
    
    private Connection sqlConnection;

The code then extends the class constructor. While the constructor for the base class takes one argument, the constructor for each of the implementation classes takes three arguments: the MusicAlbum, a string that represents a SQL statement, and a JDBC connection. For example, the constructor for MusicAlbumUpdateCommand looks like this:

    public MusicAlbumUpdateCommand(MusicAlbum album,
            Connection sqlConnection, String sqlStatement)
    {
        super(album);
        this.sqlConnection = sqlConnection;
        this.sqlStatement = sqlStatement;
        logger.debug("Creating instance " + this + ": " + sqlStatement);
    }

Finally, the code for each command implements the execute method in exactly the same way. First, it uses the instantiated connection to create a JDBC Statement object using the instantiated string. Then it executes the statement.

    public void execute() {
        Statement stmt = null;
        
        try {
            logger.fine("Executing instance " + this + ": " + sqlStatement);
            stmt = sqlConnection.createStatement();
            stmt.executeUpdate(sqlStatement);
        }
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        finally {
            if (stmt != null) {
                try { stmt.close(); } catch (Exception e) { /* ignore !*/ }
            }
        }
    }