Problem Solution Discussion Using Alternatives to Transactions

15.8.3 Discussion

To perform t ransact ions in Java, use your Connection obj ect t o t urn off aut o- com m it m ode. Then, aft er issuing your queries, use t he obj ect s commit m et hod t o com m it t he t ransact ion or rollback t o cancel it . Typically, you execut e t he st at em ent s for t he t ransact ion in a try block, w it h commit at t he end of t he block. To handle failures, invoke rollback in t he corresponding except ion handler: try { conn.setAutoCommit false; Statement s = conn.createStatement ; move some money from one person to the other s.executeUpdate UPDATE money SET amt = amt - 6 WHERE name = Eve; s.executeUpdate UPDATE money SET amt = amt + 6 WHERE name = Ida; s.close ; conn.commit ; conn.setAutoCommit true; } catch SQLException e { System.err.println Transaction failed, rolling back.; Cookbook.printErrorMessage e; empty exception handler in case rollback fails try { conn.rollback ; conn.setAutoCommit true; } catch Exception e2 { } }

15.9 Using Alternatives to Transactions

15.9.1 Problem

You need t o perform t ransact ional processing, but your MySQL server doesnt support t ransact ions.

15.9.2 Solution

Som e t ransact ional operat ions are am enable t o workarounds such as explicit t able locking. I n cert ain cases, you m ay not act ually even need a t ransact ion; by rewrit ing your queries, you can elim inat e t he need for a t ransact ion ent irely.

15.9.3 Discussion

Transact ions are valuable, but som et im es t hey need not be or cannot be used: • Your server m ay not support t ransact ions at all. I t m ay be t oo old or not configured wit h t he appropriat e t able handlers, as discussed in Recipe 15.2 . I n t his case, you have no choice but t o use som e kind of workaround for t ransact ions. One st rat egy t hat can be helpful in som e sit uat ions is t o use explicit t able locking t o prevent concurrency problem s. • Applicat ions som et im es use t ransact ions when t heyre not really necessary. You m ay be able t o elim inat e t he need for a t ransact ion by rewrit ing st at em ent s. This m ay even result in a fast er applicat ion.

15.9.4 Grouping Statements Using Locks