Spring+Mybatis 手动控制事务

public boolean testDelete(String jobCode) throws Exception {
      boolean flag = false;
      //1.获取事务控制管理器
      DataSourceTransactionManager transactionManager = HqznContext.getBean(
           "transactionManager", DataSourceTransactionManager.class);//这里是spring手动注入bean,也可以使用自动注入 HqznContext是一个工具类:主要用于简化spring手动注入代码
      //2.获取事务定义
      DefaultTransactionDefinition def = new DefaultTransactionDefinition();
      //3.设置事务隔离级别,开启新事务
      def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
      //4.获得事务状态
      TransactionStatus status = transactionManager.getTransaction(def);
      try {
        //5.具体的数据库操作(多个)
        BOBaseJob r = new BOBaseJob();
        r.setJobCode("SW001");
        r.setJobName("事务001");
        BOBaseJobMapper.deleteByPrimaryKey(jobCode);
        BOBaseJobMapper.insert(r);
        flag = true;
        transactionManager.commit(status);
      } catch (Exception e) {
        transactionManager.rollback(status);
      }
      return flag;
   }

 

posted @ 2016-09-07 10:42  风雨的叶  阅读(15985)  评论(0编辑  收藏  举报