【java】事务的回滚

三层框架:

1:servlet层

2:service层

3:dao层

a:实体类domain

b:工具类utils

b:TestTransaction事务与回滚

package com.zcib.utils;
import java.sql.SQLException;



public class TestTransaction {//这里不能直接抛异常,要回滚
	public static void main(String []args)  {

	String sql1="update bankaccount set account=account-100 where id=2";//转账功能
	String sql2="update bankaccount set account=account+100 where id=1";

	try{
		JDBCUtils.beginTranscation();//开启事务
		JDBCUtils.update(sql1);
		int i=4;
		if(i%2==0){
			throw new RuntimeException("D人为抛的异常!");
		}
		
		JDBCUtils.update(sql2);
		JDBCUtils.commitTranscation();//提交事务
	}//catch(SQLException | ClassNotFoundException e){
	   catch (Exception e) {//人为添加异常使用Exception接收处理,软件工程
		//完成,可回滚
	
		try {
			JDBCUtils.rollbackTranscation(); //回滚事务
		} catch (SQLException e1) {
			throw new RuntimeException(e);
		}
	}	
}
}
发布了27 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_38304672/article/details/89853606