运用一
//新建一名叫“张五”的客户,新建一与此用户关联的定单,订单表字段customer_id是“张五”客户的id号,
//id号由系统自动生成。
package common;
import net.newxy.dbm.*;
import org.apache.commons.beanutils.DynaBean;
public class Test{
public static void main(String[] args) {
TestSqlServerDao dao1=new TestSqlServerDao();
DynaDto customerDto=new DynaDto();
customerDto.set_table("customers");
customerDto.set("name","张五");
DynaDto ordersDto=new DynaDto();
ordersDto.set_table("orders");
ordersDto.set("date",net.newxy.util.DateTools.todayInTs());
Transaction tran=new Transaction();
try{
tran.begin();
Object result1=tran.call(dao1).update(customerDto);
if(result1!=null){
// result不等于空,表明是插入操作,且result中包含了自动生成的主关键字值。
ordersDto.set("customer_id",((DynaBean)result1).get("id"));
}else{
// result为空,表明是update操作,客户id保存在customerDto中。
// 此例因为没有给customerDto设置id,因而肯定是自动获得id值后作插入操作,
// result肯定不为空。
ordersDto.set("customer_id",customerDto.get("id"));
}
tran.call(dao1).update(ordersDto);
tran.commit();
}catch(Exception e2){
try {
tran.rollback();
} catch (Exception ex) {
}
System.out.println(e2.getMessage());
}
}
}
//dao类TestSqlServerDao
package common;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import net.newxy.dbm.BaseDAO;
public class TestSqlServerDao extends BaseDAO{
public TestSqlServerDao(){
super();
}
public Connection getConnection(String dsJndi) throws Exception {
Connection cn=null;
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
cn = DriverManager.getConnection(
"jdbc:microsoft:sqlserver://localhost:1433; SendStringParametersAsUnicode=false","webUser","myPass");
} catch (ClassNotFoundException ex) {
} catch (IllegalAccessException ex) {
} catch (InstantiationException ex) {
} catch (SQLException ex1) {
throw new Exception(ex1.getMessage());
}
return cn;
}
}
运用四
// 事务同时对多个数据库操作。方法是,如同dao类TestSqlServerDao,再建另一dao类Dao2,
// Dao2实现的getConnection(String dsJndi)方法获得另一数据库连接。
TestSqlServerDao dao1=new TestSqlServerDao();
Dao2 dao2=new Dao2();
Transaction tran=new Transaction();
try{
tran.begin();
......
tran.call(dao1,).update(...);
tran.call(dao2).remove(...);
......
tran.commit();
}catch(Exception e2){
try {
tran.rollback();
} catch (Exception ex) {
}
System.out.println(e2.getMessage());
}
运用六
// 事务同时对多个数据库操作,且不同数据库要求不同的隔离等级,
TestSqlServerDao dao1=new TestSqlServerDao();
Dao2 dao2=new Dao2();
Transaction tran=new Transaction();
try{
tran.begin();
......
tran.call(dao1,java.sql.Connection.TRANSACTION_READ_UNCOMMITTED).update(...);
tran.call(dao2,java.sql.Connection.TRANSACTION_NONE)).remove(...);
......
tran.commit();
}catch(Exception e2){
try {
tran.rollback();
} catch (Exception ex) {
}
System.out.println(e2.getMessage());
}