Monday, January 19, 2009

2.1.9 Savepoints

One of the features added in the JDBC 3.0 API is the Savepoint interface. A Savepoint object marks an intermediate point within a transaction and makes it possible to roll back the transaction to that point instead of rolling back the entire transaction. In other words, when a Savepoint object is passed to the Connection method rollback, it will save everything in the transaction up to the savepoint and undo everything in the transaction after the savepoint.
Creating a Savepoint object is done via the Connection method setSavepoint, as is shown in the following line of code.
Savepoint save1 = con.setSavepoint("SAVEPOINT_1");

The following code example demonstrates setting a Savepoint object in a transaction, rolling the transaction back to that Savepoint object, and then committing the part of the transaction that precedes the Savepoint object.

Statement stmt = con.createStatement();
int rows = stmt.executeUpdate("INSERT INTO AUTHORS VALUES " +
"(LAST, FIRST, HOME) 'TOLSTOY', 'LEO', 'RUSSIA'");
Savepoint save1 = con.setSavepoint("SAVEPOINT_1");

int rows = stmt.executeUpdate("INSERT INTO AUTHORS VALUES " +
"(LAST, FIRST, HOME) 'MELVOY', 'HAROLD', 'FOOLAND'");
...
con.rollback(save1);
...
con.commit();

Because the Savepoint object save1 was supplied as an argument to the method rollback, only the part of the transaction that precedes the creation of save1 has been committed, which means that Leo Tolstoy was added to the table AUTHORS but Harold Melvoy was not.
It is legal to create multiple savepoints in a transaction, which is done by calling the method setSavepoint for each savepoint to be set. Most savepoints are removed automatically. When a transaction is committed or an entire transaction is rolled back, all savepoints in it are automatically removed. If a transaction is rolled back to a savepoint, any savepoints that were set after it are automatically removed. It is also possible to remove a particular Savepoint object explicitly by supplying it as the argument to the Connection method releaseSavepoint, as is done in the following line of code.
con.releaseSavepoint(save1);
A Savepoint object that has been removed either automatically or explicitly is no longer valid, and supplying it to the method rollback will cause an SQLException to be thrown.

0 Comments: