在使用springmvc+mybatis的过程中,发现spring中的配置如下:
spring-mybatis.xml中的配置如下:
<!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="repair" propagation="REQUIRED" />
<tx:method name="delAndRepair" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
springmvc.xml配置如下:
<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
<context:component-scan base-package="com.ms.controller" />
<context:component-scan base-package="com.njzaizao">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
但是事实上 只是对controller类中进行了扫描 service层中并不能进行扫描,这样service层中就能自动开启事物了,但是在service层中不能使用try catch,若实在是要在service层中捕获到异常 则需要使用注解@Transactional 具体是示例如下:
@Transactional
@ApiOperation("上移")
@RequestMapping(value = "/upExamLib", method = RequestMethod.PUT)
public Result upExamLib(@Valid @RequestBody HomeUpForm homeForm) {
ExamLib examLib = examLibService.getExamLibById(homeForm.getId());
ExamLib examLib1 = examLibService.getExamLibById(homeForm.getUid());
if (null == examLib || null == examLib1) {
return ResultUtil.sendErrorMessage("上移失败!");
}
boolean flag = examLibService.updateExamLibSort(examLib1.getId(), examLib.getSort());
boolean flag1 = examLibService.updateExamLibSort(examLib.getId(), examLib1.getSort());
if (flag && flag1) {
return ResultUtil.sendSuccessMessage("上移成功!");
} else {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return ResultUtil.sendErrorMessage("上移失败!");
}
}