Java and Ibatis, as long as the Executexxx () method is executed, the default autocommit transaction means that each call to the Executexxx () method is an independent transaction, but for some cases, such as transfer, But the money was deducted from an account (in fact, a record was logically deleted) in another account to increase the amount of deposit (in fact, the record is modified), these 2 operations should be a transaction, either occurs, or does not occur, at this point should be the 2 operations defined as a transaction.
1, Java as long as the transaction operation is set to not automatically submit, through manual submission can achieve transaction processing, the code is as follows:
package com.oracle;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.Statement; /** * Java Transaction control * @author Administrator */public class Testtrans {/** * @param args/public static void Ma
In (string[] args) {Connection ct = null;
try{class.forname ("Oracle.jdbc.driver.OracleDriver");
ct = drivermanager.getconnection ("Jdbc:oracle:thin:@172.17.40.227:1521:orcl", "Scott", "Tiger");
Statement sm = ct.createstatement ();
Join transaction processing Ct.setautocommit (FALSE);
Sm.executeupdate ("Update emp set sal=sal-100 where ename= ' SCOTT '");
int i = 7/0;
Sm.executeupdate ("Update emp set sal=sal+100 where ename= ' SMITH '");;
Submit transaction Ct.commit ();
}catch (Exception e) {//Rollback of try{ct.rollback () if an exception occurs;
}catch (Exception ex) {ex.printstacktrace ();
} e.printstacktrace ();
}finally{Sm.close ();
Ct.close (); }
}
}
2, Ibatis mainly through the Sqlmapclient class StartTransaction (), CommitTransaction (), Endtransaction (), RollbackTransaction () These four methods implement the Start, commit, end, and fallback of a transaction. The example code is as follows:
Private Reader reader = new Resources.getresourceasreader (
"Com/ibatis/example/sqlmapconfig.xml");
Private Sqlmapclient Sqlmap = Xmlsqlmapbuilder.buildsqlmap (reader);
Public Updateitemdescription (String itemId, String newdescription) throws SQLException {
try {
Sqlmap.starttransaction ();
Item item = (item) sqlmap.queryforobject ("GetItem", itemId);
Item.setdescription (newdescription);
Sqlmap.update ("UpdateItem", item);
Sqlmap.committransaction ();
} finally {
sqlmap.endtransaction ();
}
Note: transactions cannot be nested. Calling the. StartTransaction from the same thread multiple times before the commit () or rollback () is invoked, causing an exception to be thrown. In other words, for each sqlmap instance, each thread is only
can open a transaction.