Savepoints in Java

Looking to get certified as a OCP (Java SE 17 Developer) with Oracle? Here is an article on the topic of Savepoints to prepare for this topic in the OCP exam.

What is a savepoint?

A savepoint is like a bookmark within a transaction for which autocommit is disabled. We can create a savepoint using either Connection.setSavepoint(), which returns a java.sql.Savepoint instance.

The following methods are available in the Connection interface..

setSavepoint()	Creates an unnamed savepoint
setSavepoint(String name)	Creates a savepoint with name

Rolling Back till a point

We can use savepoints to rollback till a particular point within the transaction.

We already know that the rollback() method in the Connection API can be used to rollback a transaction. For better control, we can use the overloaded Connection.rollback(Savepoint svpt) method to undo all the changes made till the mentioned savepoint.

Savepoint sp1 = conn.setSavepoint("First savepoint");
// database code
Savepoint sp2 = conn.setSavepoint("Second savepoint");
// database code
// database code

In the above code, rolling back till sp1 invalidates all the database changes done till sp1, which includes the changes till sp2. So calling conn.rollback(sp1) should never be done before calling conn.rollback(sp2). Otherwise, there will be an SQLException.

Releasing a Savepoint

The method Connection.releaseSavepoint(Savepoint) removes the savepoint from the current transaction.

If we reference a released savepoint in a rollback operation, it causes a SQLException to be thrown.


For more details on this topic, refer this link.

Leave a Reply

Your email address will not be published. Required fields are marked *