Spring使用注解进行事务管理

1、在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">

 

2、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"/>

 

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

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

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

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标识,点击能够跳转至配置事务的方法位置。mybatis

 

4、测试

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

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

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

 

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

 

参考:spa

相关文章
相关标签/搜索