Spring-事务操作

   1、什么是事务

          事务就是一系列的动作,它们被当作一个单独的工作单元,这些动作要么全部完成,要么全部不起作用。

        案例:转钱业务

          扣钱和加钱  --要么都执行要么都不执行

        JDBC  --它模式事务自动提交的

            -当代码中出现错误,转账业务就会变成eid=1的用户扣钱,eid=2的用户没有加钱,扣的钱不翼而飞了

public class Test {
    public static void main(String[] args)  {
        Connection conn=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/incast?serverTimzone=Asia/Shanghai", "root", "123456");        
            PreparedStatement statement = conn.prepareStatement("update emp set salary=salary-100 where eid=1");
            statement.executeUpdate();
            int i = 10 / 0;
            PreparedStatement statement1 = conn.prepareStatement("update emp set salary=salary+100 where eid=2");
            statement1.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
      
        }
    }

      解决方法:当代码运行错误点时事务会返回代码执行前         

public class Test {
    public static void main(String[] args)  {
        Connection conn=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/incast?serverTimzone=Asia/Shanghai", "root", "123456");
            conn.setAutoCommit(false);//设置事务手动提交
            PreparedStatement statement = conn.prepareStatement("update emp set salary=salary-100 where eid=1");
            statement.executeUpdate();
            int i = 10 / 0;//错误点
            PreparedStatement statement1 = conn.prepareStatement("update emp set salary=salary+100 where eid=2");
            statement1.executeUpdate();
            conn.commit();//事务提交
        } catch (Exception e) {
            e.printStackTrace();
            try {
            conn.rollback();//事务回滚
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }finally {
        }
    }
}

   2、如何实现Spring事务

          Spring框架一定会提供一个事务切面类。

            (1) 前置通知--开启手动事务

            (2) 后置返回通知【事务提交】

            (3) 异常通知【事务回滚】

         serviceImpl:  

@Service
public class EmpServiceImpl implements Empservice {
    @Autowired
    private EmpDao empDao;
    @Transactional//该方法交于spring的事务来管理了---默认spring不识别该注解
    @Override
    public void update(int eid, int uid, double money) {
        /*1、扣钱*/
        empDao.update(eid,-money);
        int c=1/0;
        /*2、收钱*/
        empDao.update(uid,money);
    }
    /*事务管理:(1)自己写事务管理 --自己手动定义事务切面类
    *          (2)使用spring提供的事务切面类
    * */
}

       Spring。xml

         

      pom.xml

        

 

posted @ 2023-08-17 10:21  PHOEDE  阅读(19)  评论(0)    收藏  举报