数据库事务(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表示默认存储引擎。
修改的话,另行百度吧,这里不再赘述了。