Transaction block in Java? -


what idiomatic way perform transaction in java? have code

myobject oldvar = myvar.tomyobject(); myvar.mutationanddbinsertion; myobject newvar = myvar.tomyobject(); 

i want wrap in single transaction block, sure myvar object not mutate unless database operation successful, , oldvar , newvar accurate representations of object state before , after mutation. how should approach this?

committing transactions

after auto-commit mode disabled, no sql statements committed until call method commit explicitly. statements executed after previous call method commit included in current transaction , committed unit. following method, coffeestable.updatecoffeesales, in con active connection, illustrates transaction:

public void updatecoffeesales(hashmap salesforweek) throws sqlexception {

preparedstatement updatesales = null; preparedstatement updatetotal = null;  string updatestring =     "update " + dbname + ".coffees " +     "set sales = ? cof_name = ?";  string updatestatement =     "update " + dbname + ".coffees " +     "set total = total + ? " +     "where cof_name = ?";  try {     con.setautocommit(false);     updatesales = con.preparestatement(updatestring);     updatetotal = con.preparestatement(updatestatement);      (map.entry<string, integer> e : salesforweek.entryset()) {         updatesales.setint(1, e.getvalue().intvalue());         updatesales.setstring(2, e.getkey());         updatesales.executeupdate();         updatetotal.setint(1, e.getvalue().intvalue());         updatetotal.setstring(2, e.getkey());         updatetotal.executeupdate();         con.commit();     } } catch (sqlexception e ) {     jdbctutorialutilities.printsqlexception(e);     if (con != null) {         try {             system.err.print("transaction being rolled back");             con.rollback();         } catch(sqlexception excep) {             jdbctutorialutilities.printsqlexception(excep);         }     } } {     if (updatesales != null) {         updatesales.close();     }     if (updatetotal != null) {         updatetotal.close();     }     con.setautocommit(true); } 

}

from oracle web page


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -