spring+mybatis使用事务管理不生效原因
- 检查spring的配置信息是否配置正确
<!-- 配置事务的通知:(事务的增强) -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--
propagation :事务的传播行为
isolation :事务的隔离级别
read-only :只读
rollback-for:发生哪些异常回滚
no-rollback-for:发生哪些异常不回滚
timeout :过期信息
-->
<tx:method name="transfer" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置切面 -->
<aop:config>
<!-- 配置切入点 -->
<aop:pointcut id="pointcut"
expression="execution(* com.xinrui.hospital.service.*.*(..))" />
<!-- 配置切面 -->
<aop:advisor pointcut-ref="pointcut" advice-ref="txAdvice" />
</aop:config>
其中最容易出错的点是
expression="execution(* com.xinrui.hospital.service..(…))"的写法,上述写法是正确的写法。
2.其次是在service层对于要管理的方法不要使用try-catch来捕获异常信息
package com.xinrui.hospital.service.impl;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.xinrui.hospital.bean.Account;
import com.xinrui.hospital.dao.IAccountDao;
import com.xinrui.hospital.service.IAccountService;
/**
*
* @ClassName: AccountServiceImpl
* @Description: 转账服务实现类
* @author 梁志成
* @date 2016年3月22日 下午5:26:36
*
*/
@Service(value = "accountService")
public class AccountServiceImpl implements IAccountService {
@Resource(name = "accountDao")
private IAccountDao accountDao;
/**
*
* @Title: transfer
* @Description: 转账
* @param @param out 转出账号
* @param @param in 转入账号
* @param @param money 转账金额
* @return void
*/
public boolean transfer(String out, String in, Double money) {
if (StringUtils.isNotEmpty(out) && StringUtils.isNotEmpty(in)) {
Account outAccount = new Account();
outAccount.setMoney(money);
outAccount.setName(out);
accountDao.outMoney(outAccount);
int i = 1 / 0;
Account inAccount = new Account();
inAccount.setMoney(money);
inAccount.setName(in);
accountDao.inMoney(inAccount);
}
return false;
}
}
上述是正确的配置。
3.确保事务交由spring管理
<!-- 配置由spring扫描的注解 -->
<context:component-scan base-package="com.xinrui.hospital"
use-default-filters="true">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 配置由Spring-mvc扫描的注解 -->
<context:component-scan base-package="com.xinrui.hospital.action"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
上述是正确的配置。