spring+mybatis 手动开启和提交事务

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

spring配置文件 

事务控制管理器transactionManager

  
    
  


    

示例java代码 

// 保存信息
    public MessageTpl saveMessage(Map mqInfo, Message message) throws Exception{
        // 保存信息
        //获取Spring容器的对象
      ClassPathXmlApplicationContext contextLoader = new ClassPathXmlApplicationContext(
				          new String[] { "classpath*:spring/applicationContext.xml", "classpath*:spring/spring-mybatis.xml"});
//1.获取事务控制管理器
        DataSourceTransactionManager transactionManager = contextLoader.getBean(
        "transactionManager", DataSourceTransactionManager.class);
        //2.获取事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        //3.设置事务隔离级别,开启新事务
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        //4.获得事务状态
        TransactionStatus transactionStatus = transactionManager.getTransaction(def);
        MessageTpl messageTpl = null;
        try {
            Date time = new Date();
            String status = Constant.MESSAGE_STATUS_TO_BE_CONFIRMED;
            String remark = "optId:"+mqInfo.get("userId")+"|预发布:待确认";
            if (Constant.MQ_IS_CONFIRM_NO == (Integer) mqInfo.get("isConfirm")) {
                status = Constant.MESSAGE_STATUS_TO_BE_SEND;
                remark = "optId:"+mqInfo.get("userId")+"|待发送:消息不需要确认";
            }

            messageTpl = new MessageTpl((Long) mqInfo.get("mqId"), message.getContent(), 0,
                    (Long) mqInfo.get("userId"), status, time, time, Constant.MSG_TABLE + message.getQueueName(),
                    MD5Util.MD5_32(message.getContent()));
            messageDao.saveMessage(messageTpl);
            // TODO添加缓存
            // 保存日志
            MessageLogTpl log = new MessageLogTpl(null, "预发布", status, remark, time,
                    Constant.MSG_LOG_TABLE + message.getQueueName());
            this.messageDao.saveMessageLog(log);
            
        } catch (Exception e) {
            transactionManager.rollback(transactionStatus);
            messageTpl = null;
            logger.error("saveMessage_Exception ", e);
        }finally {     
            transactionManager.commit(transactionStatus); 
        } 
        return messageTpl;
    }

 

转载于:https://my.oschina.net/sprouting/blog/911241

你可能感兴趣的:(spring+mybatis 手动开启和提交事务)