ssm框架 mysql事务管理_SSM框架+MySQL数据库配置事务管理

本文介绍了SSM框架中数据库事务管理的配置和使用,包括在service层添加@Transactional注解来确保转账操作的原子性,以及在controller层通过try-catch进行异常处理。事务的正确配置和使用能保证数据一致性,避免出现半成功状态。同时,强调了MySQL数据库引擎需为INNODB以支持事务。
摘要由CSDN通过智能技术生成

数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行。

例如银行转账,A账户转100元给B账户,正常的流程是A账户减掉100元,B账户增加100元。如果转账失败的话,不能出现A账户已经减掉100元而B账户没有增加100元的情况。这个时候就需要用到事务,要么B账户增加了100元,全部执行完成,要么全部不执行。

SSM框架中事务的配置步骤如下:

首先配置spring-mybatis.xml,加入以下:

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

如果报错的话,在开头部分加入以下:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.1.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

然后去需要进行事务管理的service层实现方法上加入@Transactional:

@Transactional

@Override

public int addNewOrder(Map params) {

int result = 0;

//新增订单

result = orderDao.addNewOrder(params);

if(result > 0){

int uid = Integer.parseInt(params.get("uid").toString());

//新增订单详情

int outcome = orderDao.addNewOrderItem(uid);

if(outcome > 0){

//扣除金额

...

//减去商品库存

...

//清空购物车

...

}else{

throw new RuntimeException("新增订单详情失败");

}

}else{

throw new RuntimeException("新增订单失败");

}

return result;

}

以订单付款为例子,部分代码省略,能看懂意思就行。接着在controller层try catch一下:

int result =0;

try {

result = orderService.addNewOrder(params);

} catch (Exception e) {

System.out.println(e.getMessage());

}

return result;

这样,就可以对数据库进行事务管理了。

另外补充一点,我在查阅SSM+MySQL事务管理的时候,有博主提到需要设置MySQL的数据库引擎为INNODB,我的默认是INNODB,不是的话需要修改为INNODB。查看数据库引擎的方法:进入cmd,输入mysql -u root -p,回车然后输入密码,接着输入:show engines;字段 Support为:Default表示默认存储引擎。

修改的话,另行百度吧,这里不再赘述了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值