Recording a customer's shopping cart as an order 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&lt;String, CartItem&gt; 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.
Using the "try-with-resources" statement should clean up your code significantly. There are two advantages:


It allows you to declare your resources (in this case Connection and Statement objects) in exactly the scope they're going to be used. This means you don't have to first initialize them to null, which is ugly.
It will ensure your resources get closed no matter what.


Also, you should probably print the stack trace (to aid you and others in debugging), and you should print your error messages to stderr instead of stdout.

public long insertOrder(Customer customer, Hashtable&lt;String, CartItem&gt; shoppingCart)
{
    try (Connection connection = MySqlConnection.getConnection();
        Statement statement = connection.createStatement();) {
        connection.setAutoCommit(false);
        long orderId = System.currentTimeMillis();
        OrderPeer.insertOrder(statement, orderId, customer);
        OrderDetailsPeer.insertOrderDetails(statement, orderId, shoppingCart);
        connection.commit();
        return orderId;
    } catch (SQLException e) {
        try {
           connection.rollback();
        } catch (Exception ex) {
            System.err.println("Could not roll back connection: " + ex.getMessage())
            ex.printStackTrace();

        }
        System.err.println("Could not insert order: " + e.getMessage());
        e.printStackTrace()l
        return 0;
    }
}