springboot事務管理

1、設置SpringBoot事務

springboot項目要使用事務必須要開啓@EnableTransactionManagement註解。這個註解有且僅有在啓動類上面有一個註解,不能有重複。如下面的代碼中:

package com.qlys.security;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.qlys.security.service.impl.RedisCache;


@SpringBootApplication
@EnableFeignClients
@EnableTransactionManagement
@EnableCircuitBreaker
@EnableDiscoveryClient
public class ServiceSecurityAbilityApplication {

	
	
	public static void main(String[] args) {
		SpringApplication.run(ServiceSecurityAbilityApplication.class, args);
	}

}

在啓動類中設置了EnableTransactionManagement註解後,下一步就是在需要進行事務處理的方法上面加入對應的@Transactional註解了。這裏有一個需要注意的地方,springboot默認對拋出RuntimeException異常的方法進行加滾。因此如果我們需要自定義自己的異常需要在Transactional註解上加入rollbackFor這個屬性。如下面的代碼就是指定當拋出Exception異常時回滾。

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean insert(AccountModel account) throws Exception {

因此在我們的事務不進行回滾時,儘量檢查這二個地方,一個是啓動類上面是否啓用了事務註解或者是否有重複的啓動註解。另一個是事務註解對應的方面上面是否爲招聘RuntimeException或者是否設置了自定義的回滾異常

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章