Spring使用注解进行事务管理

一、在spring配置文件中加入命名空间

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

 

二、spring配置文件

    <!-- 事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--  数据源 源自于mybatis,也就是看dao.xml-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 注解方式配置事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

 

三、类或接口的顶部加注解

1.设置某个方法使用事务

在调用的方法上加上@Transactional注解(必须为public方法才行,不要捕捉异常,要让异常自动抛出,否则不能进行事务回滚。方法要写在服务层中在controller中无效)。

public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleDao daoImpl;

    @Transactional    // 设置某个方法使用事务
    public int add(Role role) {
         
    }
}

 

2.设置某个类的所有方法都使用事务

@Service
@Transactional    // 类中所有方法都使用事务
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleDao daoImpl;

    @Override
    public int add(Role role) {
        return daoImpl.add(role);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)  // 不使用事务
    public List<Role> queryList() {
        return daoImpl.queryList();
    }
}

 

配置完成后可以在IDEA中看到,在spring配置文件左侧出现了一个m标识,点击可以跳转至配置事务的方法位置。

 

四、测试

 如果没有使用事务,先添加角色,再人为制造一个异常。程序报异常后,数据库中任然插入了数据。

使用食物后,出现异常后,数据库就会回滚,不会插入数据。

    @Override
    @Transactional
    public int add(Role role) {
        int affectRows = daoImpl.add(role);    // 添加角色
        
        int arr[] = {};
        arr[10] = 0;
        return affectRows;
    }

 

现在有一个需求,我的MySQL数据库主键(int类型)是自动增长,每次插入失败主键增长了但没有插入成功,下一次加入成功后会造成数据的主键不连续。目前上述事务处理方式并不能解决这个需求。

 

参考:

 

posted @ 2019-08-20 18:03  柯西丶不是你  阅读(2234)  评论(0编辑  收藏  举报