Savepoints allow the setting of "staging points" in a transaction. Savepoints are checkpoints that the application can roll back to without throwing away the entire transaction. Savepoints are new in JDBC 3.0, meaning that the application must run on Java™ Development Kit (JDK) 1.4 or a subsequent release to use them. Moreover, savepoints are new to the Developer Kit for Java, meaning that savepoints are not supported if JDK 1.4 or a subsequent release is not used with previous releases of the Developer Kit for Java.
Savepoints can be set throughout the work of a transaction. The application can then roll back to any of these savepoints if something goes wrong and continue processing from that point. In the following example, the application inserts the value FIRST into a database table. After that, a savepoint is set and another value, SECOND, is inserted into the database. A rollback to the savepoint is issued and undoes the work of inserting SECOND, but leaves FIRST as part of the pending transaction. Finally, the value THIRD is inserted and the transaction is committed. The database table contains the values FIRST and THIRD.
Example: Set and roll back to savepoints
Statement s = Connection.createStatement(); s.executeUpdate("insert into table1 values ('FIRST')"); Savepoint pt1 = connection.setSavepoint("FIRST SAVEPOINT"); s.executeUpdate("insert into table1 values ('SECOND')";); connection.rollback(pt1); // Undoes most recent insert. s.executeUpdate("insert into table1 values ('THIRD')"); connection.commit();
Although it is unlikely to cause problems to set savepoints while in auto-commit mode, they cannot be rolled back as their lives end at the end of a transaction.
Savepoints can be released by the application with the releaseSavepoint method on the Connection object. Once a savepoint has been released, attempting to roll back to it results in an exception. When a transaction commits or rolls back, all savepoints automatically release. When a savepoint is rolled back, other savepoints that follow it are also released.