I have come up with the following method to post a transaction to a database, in the context of an e-commerce Java web application. The transaction consists in submitting a new order alongside its details:
public long insertOrder(Customer customer, Hashtable<String, CartItem> shoppingCart)
{
long returnValue = 0L;
Connection connection = null;
Statement statement = null;
try {
connection = MySqlConnection.getConnection();
connection.setAutoCommit(false);
statement = connection.createStatement();
long orderId = System.currentTimeMillis();
OrderPeer.insertOrder(statement, orderId, customer);
OrderDetailsPeer.insertOrderDetails(statement, orderId, shoppingCart);
connection.commit();
returnValue = orderId;
} catch (SQLException e) {
try { connection.rollback(); } catch (Exception ex) { }
System.out.println("Could not insert order: " + e.getMessage());
} finally {
try { statement.close(); } catch (Exception e) { }
try { connection.close(); } catch (Exception e) { }
}
return returnValue;
}
I would like to know if I am handling the exception, rolling back, and closing the statement/connection in the best possible manner.