首页 > 代码库 > spring+mybatis 手动开启和提交事务
spring+mybatis 手动开启和提交事务
spring配置文件
事务控制管理器transactionManager
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
示例java代码
// 保存信息 public MessageTpl saveMessage(Map<String, Object> 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; }
spring+mybatis 手动开启和提交事务
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。