|
Using savepoints
The Savepoint interface contains
methods to set, release, or roll back a transaction to designated savepoints.
Once a savepoint has been set, the transaction can be rolled back to that
savepoint without affecting preceding work. Savepoints provide finer-grained
control of transactions by marking intermediate points within a transaction.
Setting and rolling back to a savepoint
The Connection.setSavepoint method sets a savepoint within the current
transaction. The Connection.rollback method is overloaded to take a
savepoint argument.
The code example below inserts a row into a table, sets the savepoint
svpt1, and then inserts a second row. When the transaction is
later rolled back to svpt1, the second insertion is undone, but
the first insertion remains intact. In other words, when the transaction is
committed, only the row containing '1' will be added to TABLE1.
conn.setAutoCommit(false); // Autocommit must be off to use savepoints.
Statement stmt = conn.createStatement();
int rows = stmt.executeUpdate("INSERT INTO TABLE1 (COL1) VALUES(1)");
// set savepoint
Savepoint svpt1 = conn.setSavepoint("S1");
rows = stmt.executeUpdate("INSERT INTO TABLE1 (COL1) VALUES (2)");
...
conn.rollback(svpt1);
...
conn.commit();
Releasing a savepoint
The method Connection.releaseSavepoint takes a Savepoint object
as a parameter and removes it from the current transaction. Once a savepoint
has been released, attempting to reference it in a rollback operation will
cause an SQLException to be thrown.
Any savepoints that have been created in a transaction are automatically
released and become invalid when the transaction is committed or when the
entire transaction is rolled back.
Rolling a transaction back to a savepoint automatically releases and makes
invalid any other savepoints created after the savepoint in question.
Rules for savepoints
The savepoint cannot be set within a batch of statements to enable partial
recovery. If a savepoint is set any time before the method executeBatch
is called, it is set before any of the statements that have been added to the
batch are executed.
A savepoint can be reused after it has been released explicitly (by issuing a
release of the savepoint) or implicitly (by issuing a connection
commit/rollback to that savepoint or to a savepoint declared earlier than that
savepoint).
It is possible to nest savepoints, but only in an embedded environment.
|