Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 10 Building Database Applications with JDBC

Rolling Back Database Operations

In the last example (Listing 10-11), you used a method called rollback() using a Connection object. This method is used to roll back all the uncommitted operations in a transaction.

What happens if you remove the rollback statement from the last example? If your answer is that it will work given a successful condition, but the program will not work in case of an exception (since the rollback() method call is missing), you are wrong. The program will work in both conditions. Yes, in both the conditions! Okay, then why are you using the rollback() at all? The answer is given in the following three points:

The above example illustrates a two-operation transaction that is quite simple. In this case, explicit rollback() will not change anything. However, in case of a multi-stage transaction where you can define various milestones (in the form of savepoints, which we will discuss shortly), rollback plays a vital role. Unfinished or incomplete subtransaction states may cause inconsistencies.

If your connection object is a pooled connection object, then it makes sense to call rollback(). In case of a pooled connection object, the connection object will be reused later, and at that time unfinished operations may cause inconsistencies.

In general, using the rollback() method in failed cases is always recommended.

In case of a large transaction, you can divide the transaction into multiple subtransactions. In other words, you can define multiple milestones to complete the transaction. These milestones are referred to as savepoints, and Java abstraction for this concept is java.sql.Savepoint interface. Once a transaction completes a certain milestone, that point can be saved as a Savepoint and operations performed till that point can be committed. In case a failure occurred later, while executing other database operations, you can rollback the database till your last defined and

saved savepoint. This way, you need not carry the whole lengthy transaction all over again; you can start from the last saved savepoint. Listing 10-12 demonstrates how to use savepoints.

Listing 10-12.  DbSavepoint.java

import java.sql.*;

// To illustrate how to use savepoints with commits and rollbacks class DbSavepoint {

public static void main(String[] args) throws SQLException { Connection connection = DbConnector.connectToDb(); ResultSet resultSet = null;

//we're using explicit finally blocks

//instead of try-with-resources statement in this code try {

//for commit/rollback we first need to set auto-commit to false connection.setAutoCommit(false);

Statement statement = connection.createStatement(

ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

resultSet = statement.executeQuery("SELECT * FROM familyGroup");

System.out.println("Printing the contents of the table before inserting"); while(resultSet.next()) {

System.out.println(resultSet.getInt("id") + " " + resultSet.getString("nickName"));

}

304

Chapter 10 Building Database Applications with JDBC

System.out.println("Starting to insert rows");

//first insert resultSet.moveToInsertRow(); resultSet.updateString("nickName", "Tom"); resultSet.insertRow(); System.out.println("Inserted row for Tom");

//our first savepoint is here. . .

Savepoint firstSavepoint = connection.setSavepoint();

//second insert resultSet.moveToInsertRow(); resultSet.updateString("nickName", "Dick"); resultSet.insertRow(); System.out.println("Inserted row for Dick");

//our second savepoint is here. . . after we inserted Dick

//we can give a string name for savepoint

Savepoint secondSavepoint = connection.setSavepoint("SavepointForDick");

//third insert resultSet.moveToInsertRow(); resultSet.updateString("nickName", "Harry"); resultSet.insertRow();

System.out.println("Inserted row for Harry");

//our thrid savepoint is here. . . for "Harry"

Savepoint thirdSavepoint = connection.setSavepoint("ForHarry"); System.out.println("Table updation complete. . .");

//rollback to the state when Dick was inserted;

//so the insert for Harry will be lost System.out.println(

"Rolling back to the state where Tom and Dick were inserted"); connection.rollback(secondSavepoint);

//commit the changes now and see what happens to the contents of the table connection.commit();

System.out.println("Printing the contents of the table after commit"); resultSet = statement.executeQuery("SELECT * FROM familyGroup"); while(resultSet.next()) {

System.out.println(resultSet.getInt("id") + " "

+resultSet.getString("nickName"));

}

} catch (SQLException e) {

System.out.println("Something gone wrong, couldn't add a contact in family group"); // roll back all the changes in the transaction since something has gone wrong connection.rollback();

e.printStackTrace();

}

305

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]