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類型)是自動增長,每次插入失敗主鍵增長了但沒有插入成功,下一次加入成功后會造成數據的主鍵不連續。目前上述事務處理方式並不能解決這個需求。

 

參考:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM