Table of Contents
Spring transaction management operation method
Home Java javaTutorial Spring transaction management operation method

Spring transaction management operation method

Jun 20, 2017 pm 04:20 PM
spring affairs statement question

Question, I did add the annotation @Transactional to the service as usual. Why do I still find data inconsistencies when querying the database? I think it must be that the transaction did not work and an exception occurred. The data is not rolled back. So I tested the relevant code, and found that I had stepped into two pits. It was indeed the data inconsistency caused by the transaction not being rolled back. Let’s summarize the lessons learned:

Spring transaction management operation method

  • Programmatic transaction management

    • Rarely used in actual applications

    • Manually manage transactions by using TransactionTemplate

  • ##Declarative Transaction management

    • Recommended for development (minimum code intrusion)

    • Spring’s declarative transaction is implemented through AOP

#Mainly master declarative transaction management.

Two reasons why spring transactions are not rolled back

To summarize the two reasons why transactions are not rolled back, one is the internal method call of the Service class, and the other is the try...catch exception.

1. Service class internal method call
Probably there is a method A in Service, which will call method B internally. Method A has no transaction management, and method B uses declarative transactions. Declare Transactional annotation on the method for transaction management. The sample code is as follows:

@Servicepublic class RabbitServiceImpl implements RabbitService {

    @Autowiredprivate RabbitDao rabbitDao;
    @Autowiredprivate TortoiseDao tortoiseDao;

    @Overridepublic Rabbit methodA(String name){return methodB(name);
    }

    @Transactional(propagation = Propagation.REQUIRED)public boolean methodB(String name){
        rabbitDao.insertRabbit(name);
        tortoiseDao.insertTortoise(name);return true;
    }

}
Copy after login
The unit test code is as follows:

public class RabbitServiceImplTest {

    @Autowiredprivate RabbitService rabbitService;// 事务未开启    @Testpublic void testA(){
        rabbitService.methodA("rabbit");
    }// 事务开启    @Testpublic void testB(){
        rabbitService.methodB("rabbit");
    }
}
Copy after login
As you can see from the previous section, declarative transactions are passed AOP dynamic proxy is implemented, which will generate a proxy class for transaction management, but the target class (service) itself cannot perceive the existence of the proxy class.

For methods annotated with @Transactional, when calling the method of the proxy class, the transaction will be started through the interceptor TransactionInterceptor, and then the method of the target class will be called. Finally, after the call is completed, the TransactionInterceptor will Submit or rollback a transaction, the general process is as follows:

Spring transaction management operation method

#Summary, when calling method B in method A, it is actually through the reference of "this", that is, directly calling method of the target class instead of the proxy class obtained through the Spring context, so the transaction will not be started.

2. try...catch exception
The database exception is processed in a piece of business logic, using the try...catch clause to capture the exception and throw a custom exception , this situation resulted in the transaction not being rolled back. The sample code is as follows:

@Transactional(propagation = Propagation.REQUIRED)public boolean methodB(String name) throws BizException {try {
        rabbitDao.insertRabbit(name);
        tortoiseDao.insertTortoise(name);
    } catch (Exception e) {throw new BizException(ReturnCode.EXCEPTION.code, ReturnCode.EXCEPTION.msg);
    }return true;
}
Copy after login
The definition of BizException is as follows:

public class BizException extends Exception {// 自定义异常}
Copy after login
in the above code When an exception occurs in a declarative transaction, the transaction will not be rolled back. Although I caught the exception in the code, I also threw an exception at the same time. Why was the transaction not rolled back? I guessed that the exception type was wrong, so I started to search for the reason, looked through Spring's official documentation, and found the answer. The following is translated from the Spring official website.

17.5.3 Rollback of declarative transactions
The previous section introduced how to set up Spring transactions, which are generally set in the Service layer code of your application. This section will introduce How to control transaction rollback in simple and popular declarative transactions.

The recommended transaction rollback method in the Spring FrameWork transaction framework is to throw an exception in the currently executing transaction context. If the exception is not handled, Spring FrameWork's transaction framework code will catch any unhandled exception when the exception is thrown up the call stack, and then decide whether to mark the transaction for rollback.

  • In the default configuration, the transaction framework code of Spring FrameWork will only mark transactions with

    runtime, unchecked exceptions as rollback; that is to say, throwing in the transaction The exception that occurs is RuntimeException or its subclass, so that the transaction will be rolled back (Error will also cause the transaction to be rolled back by default). With the default configuration, all checked exceptions will not cause transaction rollback.

Note: Unchecked Exception includes Error and RuntimeException. All subclasses of RuntimeException also belong to this category. The other type is checked Exception.

  • #You can precisely configure the exception type and specify transaction rollback for this exception type, including checked exceptions. The following XML code snippet shows how to configure checked exceptions to cause transaction rollback and apply a custom exception type:

<advice>
  <attributes>
  <method></method>
  <method></method>
  </attributes>
</advice>
Copy after login
Copy after login
The annotation form with the same effect is as follows:

@Transactional(rollbackForClassName={"Exception"})
或者
@Transactional(rollbackFor={Exception.class})
Copy after login
  • 在你遇到异常不想回滚事务的时候,同样的你也可指定不回滚的规则,下面的一个例子告诉你,即使遇到未处理的 InstrumentNotFoundException 异常时,Spring FrameWork 的事务框架同样会提交事务,而不回滚。

<advice>
  <attributes>
  <method></method>
  <method></method>
  </attributes>
</advice>
Copy after login
Copy after login

  与其有同样作用的注解形式如下:   

@Transactional(noRollbackForClassName={"InstrumentNotFoundException"})
或者
@Transactional(noRollbackFor={InstrumentNotFoundException.class})
Copy after login
  • 还有更灵活的回滚规则配置方法,同时指定什么异常回滚,什么异常不回滚。当Spring FrameWork 的事务框架捕获到一个异常的时候,会去匹配配置的回滚规则来决定是否标记回滚事务,使用匹配度最强的规则结果。因此,下面的配置例子表达的意思是,除了异常 InstrumentNotFoundException 之外的任何异常都会导致事务回滚。

<advice>
  <attributes>
  <method></method>
  </attributes>
</advice>
Copy after login
  • 你也可以通过编程式的方式回滚一个事务,尽管方法非常简单,但是也有非常强的代码侵入性,使你的业务代码和Spring FrameWork 的事务框架代码紧密的绑定在一起,示例代码如下:

public void resolvePosition() {  try {      // some business logic...
  } catch (NoProductInStockException ex) {      // trigger rollback programmatically      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
  }
}
Copy after login

  如果可能的话,强烈推荐您使用声明式事务方式回滚事务,对于编程式事务,如果你强烈需要它,也是可以使用的,but its usage flies in the face of achieving a clean POJO-based architecture.(没懂...)

看完官方文档这节内容找到了问题的答案,原来是因为我们自定义的异常不是 RuntimeException。我的解决办法是,在注解@Transactional中添加 rollbackFor={BizException.class}。可能你会问我为什么不将自定义异常修改为继承RuntimeException,因为我需要BizException是一个checked 异常。

The above is the detailed content of Spring transaction management operation method. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

MySQL transaction processing: the difference between automatic submission and manual submission MySQL transaction processing: the difference between automatic submission and manual submission Mar 16, 2024 am 11:33 AM

MySQL transaction processing: the difference between automatic submission and manual submission. In the MySQL database, a transaction is a set of SQL statements. Either all executions are successful or all executions fail, ensuring the consistency and integrity of the data. In MySQL, transactions can be divided into automatic submission and manual submission. The difference lies in the timing of transaction submission and the scope of control over the transaction. The following will introduce the difference between automatic submission and manual submission in detail, and give specific code examples to illustrate. 1. Automatically submit in MySQL, if it is not displayed

PHP PDO Tutorial: An Advanced Guide from Basics to Mastery PHP PDO Tutorial: An Advanced Guide from Basics to Mastery Feb 19, 2024 pm 06:30 PM

1. Introduction to PDO PDO is an extension library of PHP, which provides an object-oriented way to operate the database. PDO supports a variety of databases, including Mysql, postgresql, oracle, SQLServer, etc. PDO enables developers to use a unified API to operate different databases, which allows developers to easily switch between different databases. 2. PDO connects to the database. To use PDO to connect to the database, you first need to create a PDO object. The constructor of the PDO object receives three parameters: database type, host name, database username and password. For example, the following code creates an object that connects to a mysql database: $dsn="mysq

How to solve the problem that jQuery cannot obtain the form element value How to solve the problem that jQuery cannot obtain the form element value Feb 19, 2024 pm 02:01 PM

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

How does Java database connection handle transactions and concurrency? How does Java database connection handle transactions and concurrency? Apr 16, 2024 am 11:42 AM

Transactions ensure database data integrity, including atomicity, consistency, isolation, and durability. JDBC uses the Connection interface to provide transaction control (setAutoCommit, commit, rollback). Concurrency control mechanisms coordinate concurrent operations, using locks or optimistic/pessimistic concurrency control to achieve transaction isolation to prevent data inconsistencies.

See all articles