Spring Boot Road Primer (13) --- Spring Boot implemented transaction management

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Geffin/article/details/100603660

1 Introduction

We all know that there are transaction management in Spring programmatic and declarative in two ways. Among them, programmatic transaction is achieved by encoding the transaction, and declarative transaction-based AOP. Since the transaction statement and transaction specific business logic decoupling, so a wide range of applications. This article will introduce @Transactional annotation-based declarative transaction implementation form.

Note 2

  1. In the default configuration, Spring will only roll back inherit from RuntimeException exception or Error.
  2. Only apply to public methods, @ Transactional annotations take effect.

Here I will brief you classify Java exception. Which Throwable is the root of all exceptions, and Throwable Error and Exception can be divided into two categories. In addition, internal Exception can be divided into two categories, one for the Checked Exception, you can check the anomaly, also known as the compiler exceptions, which we must use the try-catch to handle, the other for RuntimeException, namely runtime exceptions, which kinds of abnormal taken over by the virtual machine, we can not handle.

The easiest to use 3

Want to use transaction management in Spring Boot, just add @Transactional comment on the method.

package edu.szu.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import edu.szu.test.entity.Book;
import edu.szu.test.service.BookService;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TestApplication.class})
public class MyTest {
	
	@Autowired
	BookService bookService;
	
	@Test
    public void test(){
		Book book = new Book();
		book.setName("Tony1");
		book.setPrice((float)13);
		
		bookService.insert(book);
		
		int i = 1/0;
	}
	
}

Let us not use @Transactional annotations, insert random piece of data, we can see that although behind the program there was a mistake, but it has been inserted in front of the data or database.

Here Insert Picture Description
Now we try to implement transaction management in Spring Boot, before adding @Transactional annotation method to see if the data will be inserted into the database?

package edu.szu.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import edu.szu.test.entity.Book;
import edu.szu.test.service.BookService;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TestApplication.class})
public class MyTest {
	
	@Autowired
	BookService bookService;
	
	@Test
	@Transactional
    public void test(){
		Book book = new Book();
		book.setName("Tony2");
		book.setPrice((float)14);
		
		bookService.insert(book);
		
		int i = 1/0;
	}
	
}

We found that after adding @Transactional notes, after the program throws an exception, the transaction is automatically rolled back, we realized the Spring Boot simplest transaction management.

4 @Transactional annotation section describes the attributes

value/transactionManager

When configured with multiple transaction managers can use the value attribute specifies the property or transactionManager choose which transaction manager. Whether JDBC or JPA interfaces and so achieve self PlatformTransactionManager. If added it is spring-boot-starter-jdbc dependency injection DataSourceTransactionManager default frame instance. If added is spring-boot-starter-data-jpa dependency injection JpaTransactionManager default frame instance.

propagation

This attribute propagation behavior control matters, it defaults to Propagation.REQUIRED

Optional values ​​are as follows

  1. PROPAGATION_REQUIRED: Indicates the current method must run within a transaction. If the current transaction exists, the method will run in that transaction. Otherwise, it will start a new transaction
  2. PROPAGATION_SUPPORTS: Indicates the current method does not require transaction context, but if there is a current transaction, then the process will run in that transaction
  3. PROPAGATION_MANDATORY: indicates that the method must be run within a transaction, if the transaction does not currently exist, it will throw an exception
  4. PROPAGATION_REQUIRED_NEW: Indicates the current method must run in its own transaction. A new transaction will be started. If there is a current transaction, during the execution of the method, the current transaction will be suspended. If you are using JTATransactionManager, then you need to access TransactionManager
  5. PROPAGATION_NOT_SUPPORTED: indicates that the method should not be run in a transaction. If there is a current transaction, the duration of the method, the current transaction will be suspended. If you are using JTATransactionManager, then you need to access TransactionManager
  6. PROPAGATION_NEVER: Indicates the current method should not be run in a transaction context. If there is a transaction is currently running, an exception is thrown
  7. PROPAGATION_NESTED: means that if there is already a current transaction, which will run in a nested transaction. Independently nested transaction within the current transaction commit or rollback alone. If the current transaction does not exist, then it behaves as PROPAGATION_REQUIRED. Note that each vendor support for the spread of this behavior is somewhat different. You can refer to the Resource Manager documentation to confirm whether they support nested transactions

isolation

That transaction isolation level, the default value Isolation.DEFAULT.

  1. ISOLATION_DEFAULT back-end database default isolation level
  2. ISOLATION_READ_UNCOMMITTED lowest isolation level, allowing the read data changes have not been submitted, may cause dirty reads, non-repeatable reads or phantom reads
  3. ISOLATION_READ_COMMITTED allow concurrent transactions to read data already submitted, can prevent dirty reads, but phantom reads or non-repeatable read may still occur
  4. ISOLATION_REPEATABLE_READ repeatedly read the results on the same field are the same, unless the data is modified their affairs themselves, can prevent dirty reads and non-repeatable reads, but phantom reads still occur
  5. ISOLATION_SERIALIZABLE highest level of isolation, full compliance ACID isolation levels, to ensure that prevent dirty reads, non-repeatable read and phantom read, but also the slowest transaction isolation level, as it usually is achieved by completely locking transaction related database tables

timeout

Transaction timeout, the default value is -1. If you exceed the time limit but the transaction has not been completed, it automatically rolls back the transaction.

readOnly

Specify whether the transaction is read-only transactions, the default value is false. In order to approach ignores that do not require a transaction, such as reading data, you can set read-only to true.

rollbackFor

Is used to specify the type of transaction rollback can trigger an exception, you can specify multiple exception types.

noRollbackFor

Specify the type of exception is thrown, not roll back the transaction, you can specify multiple exception types.

Reference: the Spring annotation configuration @Transactional use the Boot transaction management

Guess you like

Origin blog.csdn.net/Geffin/article/details/100603660