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

时间:2022-08-01 17:36:56

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;
}