JTA事务和普通JDBC事务回滚实例

下面给出了回滚JDBC事务的代码示例:

public void processT(String orders) {
Context initCtx = new InitialContext();
javax.sql.DataSource ds = javax.sql.DataSource)initCtx.lookup
(“java:comp/env/jdbc/OrdersDB”);
java.sql.Connection conn = ds.getConnection();
try{
conn.setAutoCommit( false ); //更改JDBC事务的默认提交方式
orderNo = createOrder( orders );
updateOrderStatus(orderNo, “orders created”);
conn.commit();//提交JDBC事务
}catch( Exception e ){
try{
conn.rollback();//回滚sJDBC事务
throw new EJBException(“事务回滚: “ + e.getMessage());
}catch( SQLException sqle ){
throw new EJBException(“出现SQL操作错误: “ + sqle.getMessage());
}
}
}

 

下面给出了JTA事务代码示例:

public void processOrder(String orderMessage) {
UserTransaction transaction = mySessionContext.getUserTransaction();//获得JTA事务
try{
transaction.begin();//开始JTA事务
orderNo = sendOrder(orderMessage);
updateOrderStatus(orderNo, “order sent”);
transaction.commit();//提交JTA事务
}catch(Exception e){
try{
transaction.rollback();//回滚JTA事务
}catch(SystemException se){
se.printStackTrace();
}
throw new EJBException(“事务回滚: “ + e.getMessage());
}
}

 

展开阅读全文

没有更多推荐了,返回首页