Reputation: 3728
I have a requirement to execute sequence of select,update,insert queries in jdbc.
here is my code:
public String editRequest(){
connection = DatabaseUtil.getServiceConnection();
try {
connection.setAutoCommit(false);
executeUpdateCategory(category, ticketid);
executeUpdateSubCategory(subcategory,
ticketid);
executeUpdateItem(item, ticketid));
executeUpdateImpact(impact),ticketid));
connection.commit();
response = "Success";
} catch (SQLException e) {
rollback();
}
return response;
}
Method Definitions:
public void executeCategory(category,ticketid){
try{
//select query using connection and prepared statement
}
catch(SQLException e){
e.printstacktrace();
}
etc... methods
Note:Since it is a single transaction.So if we get any exception inside the methods it is executing some of the statements.it is calling commit()
method.
But these methods are reusable.Could any one how to catch the Exception inside editRequest method catch block so that i can rollback the transaction if any error?
Upvotes: 0
Views: 101
Reputation: 9974
Simple answer: Rethrow the exception.
Example:
public void executeCategory(category, ticketid) throws SQLException {
try {
//select query using connection and prepared statement
}
catch(SQLException e){
e.printStackTrace();
throw e;
}
}
So you can log the exception at the place where it occurs and throw it again to rollback()
.
An alternative (perhaps the better one) is to create a custom exception and rollback on this custom exception:
public void executeCategory(category, ticketid) throws CustomException {
try {
//select query using connection and prepared statement
}
catch(SQLException e){
e.printStackTrace();
throw new CustomException(e);
}
}
and in your calling code:
public String editRequest() {
connection = DatabaseUtil.getServiceConnection();
try {
connection.setAutoCommit(false);
executeUpdateCategory(category, ticketid);
// Further calls
connection.commit();
response = "Success";
} catch (CustomException e) {
rollback();
}
return response;
}
Upvotes: 2
Reputation: 1192
If you want to catch the SQLException in editRequest you need to let it propagate by adding a throws clause to each method and removing the try catch block.
Alternately you can catch the exception and wrap it in another exception that is thrown and caught in editRequest
Upvotes: 1