IT Log

Record various IT issues and difficulties.

【Spring Boot】Dive into Spring Transactions: Unraveling Core Mechanisms and Application Scenarios


Introduction

🌟🌟This episode introduces Spring transaction management~~~

🌈For interested readers, please check out my homepage: GGBondlctrl-CSDN blog

🔥 Your likes are the biggest motivation for me to keep updating                                       

🎆No need for lengthy introductions, let’s dive right in~~

Table of Contents

📚️1.Transaction

🚀1.1What is a transaction

🚀1.2 Why Do We Need Transactions

🚀1.3 Transaction Operations

📚️2.Spring Transactions

🚀2.1 Programmatic Transactions

🚀2.2 Declarative Transactions

1. Exception Handling

2. Rethrowing Exceptions

3. Compile-time Exceptions

4. Runtime Exceptions

5@transaction Property

6.@transaction Summary

📚️3. Summary

 

📚1. Transactions

🚀1.1 What are Transactions

Transactions are a set of operations that form an indivisible unit. All operations in a transaction are committed together or rolled back as a single unit to the database. This ensures that either all operations succeed or none do.

🚀1.2 Why Transactions are Needed

Consider a scenario where funds are transferred from Account A to Account B. If Account A is debited successfully but the credit to Account B fails:

If there’s no transaction, the first step succeeds and the second fails, leaving Account A reduced by 100 dollars for nothing. Using transactions ensures that this group of operations either all succeed or all fail together.

🚀1.3 Transaction Operations

In database transaction operations, the following steps are involved:

1. Start transaction/begin (begin a transaction before performing a set of operations)

2. Commit (submit the transaction if all operations in this group are successful)

3. Rollback (roll back the transaction if any operation in this group fails)

Of course, these are the transaction operation steps learned at the MySQL stage, but Spring also has its own transaction operations. Let’s continue to explore further.

📚 2. Spring Transactions

MySQL implements transactions, and so does Spring. There are two specific implementation methods:

Transaction operations in Spring can be categorized into two types:

1. Programmatic transactions (manually writing code to handle transactions)
2. Declarative transactions (using annotations to automatically start and commit transactions)

For the previous database operations with MyBatis, I will not demonstrate them here.

🚀 2.1 Programmatic Transactions

Spring Boot integrates two objects:

1. DataSourceTransactionManager (transaction manager) – used to obtain transactions, commit or roll back transactions.
2. TransactionDefinition (transaction properties) – when obtaining a transaction, you need to pass the TransactionDefinition to get a transaction with specific attributes and status.

The specific code is as follows:

Description:

It is important to note that we need to inject the transaction manager object and the transaction definition object here. These two objects are essentially used to obtain the state of the transaction, and then through the transaction manager, operations such as committing or rolling back are performed to manage our transaction status.

After performing operations on the database, we proceed with the corresponding transaction handling.

The specific log output is as follows:

At this point, the transaction has been rolled back. If a commit operation is performed, there will be a “commit” word in the log.

This is where the transaction was committed;

Of course, during my demonstration, I had to comment out one of the transactions because it’s impossible for both a commit and a rollback to happen at the same time, right? ~~~

🚀2.2Declarative Transactions

The operation here is divided into two steps, mainly through annotations to automatically start the transaction:

First step: Add dependencies

However, in this case, I added dependencies for lombok, spring web, mybatis framework, and mysql driver, but not the one mentioned here.

Second step: Add annotations

Add the @Transactional annotation to the methods where you need transactions. There’s no need to manually start or commit transactions. The transaction is automatically started when entering the method, and it’s automatically committed after execution. If an unhandled exception occurs during the process, the transaction will be rolled back automatically.

The code is as follows:

[/crayon]

[/crayon]

Of course, if an exception occurs here, the code is as follows:

[/crayon]

 At this point, a rollback will occur and the data will not be inserted into the database;

However, for all exceptions that occur, will the transaction always roll back? Of course not, it depends on the following situations

1. Exception Handling

When we handle exceptions, the code is as follows:

[/crayon]

Explanation:

Here, after catching the exception, we print the stack trace information. As a result, the transaction will be committed.

(Whether the transaction is committed or not can mainly be checked by looking for the word “commit” in the logs or observing whether data has been inserted into the database.)

2. Re-throws the exception after catching it

Code as follows:

Explanation:

After catching the arithmetic exception here, we rethrow it. At this point, it is equivalent to not handling the exception at all, and thus the transaction will be rolled back. Additionally, a manual rollback can be performed here;

After catching the exception, add:

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

At this point, a manual rollback operation will be performed.

3.Compilation-time exceptions

The code is as follows:

Explanation:

In the transaction commit process, only runtime exceptions and rerror will trigger rollback. However, in this case, compilation-time exceptions cannot be rolled back (which can generally be understood as explicit error reporting during compilation that requires manual correction; transactions do not handle it here).

 Of course, there is another scenario

Here, the transaction outcome is rollback. Why? Because we added the @SneakyThrows annotation; during decompilation, it can be seen that exceptions are caught but not handled, and are directly thrown out, making this the second scenario.

4. Transaction Time Exceptions

 Code is as follows:

Here, the transaction is directly rolled back; no further explanation is needed by the author;

5. @Transaction Annotation Properties

1. rollbackFor: Exception rollback attribute. Specifies the types of exceptions that can trigger a transaction rollback. Multiple exception types can be specified.

2. Isolation: Transaction isolation level. Default value is Isolation.DEFAULT

3. propagation: Transaction propagation mechanism. Default value is Propagation.REQUIRED

Note:

The @Transactional annotation defaults to rolling back only for runtime exceptions and Errors; non-runtime exceptions do not roll back. That is, Exceptions’ subclasses other than RuntimeException and its subclasses will not trigger a rollback.

However, we can specify rollbackFor to all exception types here, so that all exceptions will trigger a rollback; the code is as follows:

6.Summary of @transaction

@Transactional can be used to annotate methods or classes:
• When annotating a method: Only public methods are affected (other methods do not throw errors and do not take effect) [recommended]
• When annotating a class: All public methods in the annotated class with @Transactional will be affected.
Methods/classes annotated with @Transactional will automatically start a transaction before execution, and automatically commit after execution.

If an exception occurs during method execution, and it is not caught, a transaction rollback operation will occur.
If the exception is caught by the program, the method is considered successful and will still submit the transaction, but if rethrown after catching, it will roll back. For runtime exceptions, rollback will occur, but for compile-time exceptions without SneakyThrow, submission will proceed.

📚Summary

This issue mainly explained transaction concepts and Spring transactions. The author demonstrated both ways of using Spring transactions through code examples.

🌅🌅🌅~~~~Finally, we hope to encourage each other and make progress together!!!


💪💪💪This is all for this issue. If you’re interested, please follow our channel!

😊😊Looking forward to your follow!!!


, , , , , , , , ,

10 responses to “【Spring Boot】Dive into Spring Transactions: Unraveling Core Mechanisms and Application Scenarios”

  1. 总体来说,这是一篇非常值得一读的文章,对理解Spring Boot中的事务机制非常有帮助。

  2. 通过这篇文章,我明白了如何在项目中正确使用事务来保证数据的一致性和完整性。

  3. 文章内容全面,涵盖了从理论到实践的所有方面,非常适合深入学习Spring事务。

  4. 异常处理的部分也很实用,特别是在处理可能失败的操作时,了解事务回滚机制非常重要。

  5. 喜欢作者对编程式和声明式事务的详细对比,这有助于选择合适的实现方式。

  6. 对于像我这样的开发者来说,这篇文章很好地解释了为什么需要事务以及如何在实际应用中使用它们。

  7. 文章结构很好,从基本概念到Spring的实现方式逐步展开,适合新手理解事务机制。

  8. 代码示例清晰易懂,尤其是使用DataSourceTransactionManager手动管理事务的部分,对学习很有帮助。

  9. 文中通过实际案例展示了事务的重要性,让我明白了在没有事务的情况下可能会遇到的问题。

  10. 这篇文章深入浅出地解释了Spring事务的核心机制,对理解如何确保数据一致性非常有帮助。

Leave a Reply