不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2021-05-28 17:46:45  修改时间:2024-04-16 12:50:05  分类:Java框架/系统  编辑

在MyBatis配置文件spring-mybatis.xml配置数据源及支持注解事务及事务的代理方式

  • proxy-target-class="true" 事务注解可配置在实现类方法上,需要CGLIB支持
  • proxy-target-class="false" 事务注解配置在接口上,使用默认的JDK代理支持
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:/mapping/sixone/*Mapper.xml"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dao.sixone" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>    
        <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 注解方式配置事物 -->
    <tx:annotation-driven  proxy-target-class="true"    transaction-manager="transactionManager" />

在Spring MVC配置文件spring-mvc.xml配置扫描包方式包括待事务注解的Service,默认Spring MVC扫的是原生Service。

<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
<context:component-scan base-package="com.controller" >
     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />   
</context:component-scan>

在带有@Service注解的类中写事务方法,然后调用尽量不要在该类中调用,不要在事务方法try{}catch{},而是去外层捕获这样才会回滚,这里指定了回滚异常Exception.class

注意:方法必须public

@Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
public int savePayNotice(JDCreateOrder payOrder) throws Exception {
    return createOrderMapper.updateOrderByOrderNo(payOrder);
}

最后调用:

try {
    int count = savePayNotice(payOrder);
    if (count>0) {
        //ok
    } else {
        return;
    }
} catch (Exception e) {
   return;
}