」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 理解Spring Boot中的@Transactional

理解Spring Boot中的@Transactional

發佈於2024-07-29
瀏覽:697

Understanding @Transactional in Spring Boot

在Spring Boot中管理事務可以使用@Transactional註解來完成。在這篇文章中,我們將探討如何使用 @Transactional 來確保資料一致性並簡化 Spring Boot 應用程式中的錯誤處理。

1. 基本使用

要使用@Transactional,您通常會將其放置在您想要事務行為的服務類別的方法上。

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService{

    @Transactional
    public void createUser() {
        // enter your transactional code here
    }
}

2. 傳播和隔離級別

您可以指定事務的傳播和隔離等級來控制事務的行為方式:

  • 傳播:定義現有事務已在運行時事務的行為方式。

  • 隔離:定義事務的資料可見性等級。

@Transactional(propagation = Propagation.REQUIRED, 
              isolation = Isolation.READ_COMMITTED)
public void createUser() {
    // enter your transactional code here
}

3. 回滾規則

您可以指定哪些異常應觸發回溯:

@Transactional(rollbackFor = Exception.class)
public void createUser() {
    // your transactional code here
}

4. 只讀事務

如果你的方法只讀取數據,不執行任何寫入操作,可以標記為唯讀以優化效能:

@Transactional(readOnly = true)
public void getUser() {
    // your read-only code here
}

5. 類別的事務性

您也可以將@Transactional放置在類別級別,將其套用到類別中的所有方法:

@Service
@Transactional
public class UserService {

    public void getUser() {
        // transactional code
    }

    public void createUser() {
        // transactional code
    }
}

具有事務方法的範例服務

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    @Transactional
    public void saveUser() {
        // code to save data
    }

    @Transactional(readOnly = true)
    public void fetchUser() {
        // code to fetch data
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void newTransaction() {
        // code to execute in a new transaction
    }

    @Transactional(rollbackFor = {CustomException.class})
    public void performWithRollback() {
        // risky code that may throw CustomException
    }
}

概括

使用 @Transactional Spring Boot 讓您以聲明方式管理事務,準確指定您希望事務在各種場景中的行為方式。這有助於確保資料一致性並簡化應用程式中的錯誤處理。

參考

https://www.baeldung.com/spring-transactions-read-only

https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/annotations.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html

Github: https://github.com/tharindu1998/transactional-blog

版本聲明 本文轉載於:https://dev.to/tharindufdo/understanding-transactional-in-spring-boot-8ce?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3