Home  >  Article  >  Database  >  Detailed introduction to SpringBoot transactions

Detailed introduction to SpringBoot transactions

王林
王林forward
2019-08-22 18:02:233057browse

Important concepts

Auto-commit mode

For the mysql database, by default, the database is in auto-commit mode. Each statement is in a separate transaction. When the statement is executed, the transaction is implicitly committed if the execution is successful, and the transaction is implicitly rolled back if the execution fails. For normal transaction management, a group of related operations are in one transaction, so the automatic submission mode of the database must be turned off. The following is the viewing method:

Check whether the command is automatically submitted (ON means that automatic submission is turned on, The value is 1, OFF means turning off automatic submission, the value is 0):

show variables like 'autocommit';

After turning off automatic submission, the user will always be in a transaction, and the current transaction will not end until a commit or rollback statement is executed. Start a new transaction again.

DataSource connection = masterDataSource.getConnection();
connection.setAutoCommit(false);

Transaction isolation level

The isolation level refers to the degree of isolation between several concurrent transactions. Five constants representing isolation levels are defined in the TransactionDefinition interface:

1, TransactionDefinition.ISOLATION_DEFAULT: This is the default value, indicating that the default isolation level of the underlying database is used. For most databases, this value is usually TransactionDefinition.ISOLATION_READ_COMMITTED.

2, TransactionDefinition.ISOLATION_READ_UNCOMMITTED: This isolation level indicates that a transaction can read data modified by another transaction but not yet committed. This level does not prevent dirty reads, non-repeatable reads, and phantom reads, so this isolation level is rarely used. For example, PostgreSQL actually does not have this level.

3, TransactionDefinition.ISOLATION_READ_COMMITTED: This isolation level indicates that a transaction can only read data that has been submitted by another transaction. This level prevents dirty reads and is the recommended value in most cases.

4, TransactionDefinition.ISOLATION_REPEATABLE_READ: This isolation level indicates that a transaction can repeatedly execute a query multiple times throughout the entire process, and the records returned each time are the same. This level prevents dirty reads and non-repeatable reads.

5, TransactionDefinition.ISOLATION_SERIALIZABLE: All transactions are executed one by one in order, so that there is no possibility of interference between transactions. In other words, this level can prevent dirty reads and non-repeatable reads. and phantom reading. But this will seriously affect the performance of the program. Normally this level is not used.

Transaction propagation behavior

The so-called transaction propagation behavior means that if a transaction context already exists before starting the current transaction, there are several options to specify a The execution behavior of transactional methods. The TransactionDefinition definition includes the following constants indicating propagation behavior:

1, TransactionDefinition.PROPAGATION_REQUIRED: If a transaction currently exists, join the transaction; if there is no transaction currently, create it A new transaction. It's the default value.

2, TransactionDefinition.PROPAGATION_REQUIRES_NEW: Create a new transaction. If a transaction currently exists, suspend the current transaction.

3, TransactionDefinition.PROPAGATION_SUPPORTS: If there is currently a transaction, join the transaction; if there is currently no transaction, continue to run in a non-transactional manner.

4, TransactionDefinition.PROPAGATION_NOT_SUPPORTED: Run in non-transactional mode. If a transaction currently exists, the current transaction will be suspended.

5, TransactionDefinition.PROPAGATION_NEVER: Run in non-transactional mode. If a transaction currently exists, an exception will be thrown.

6, TransactionDefinition.PROPAGATION_MANDATORY: If there is currently a transaction, join the transaction; if there is currently no transaction, throw an exception.

7, TransactionDefinition.PROPAGATION_NESTED: If a transaction currently exists, create a transaction to run as a nested transaction of the current transaction; if there is currently no transaction, this value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED.

Safepoints (Savepoints)

First of all, you must know that savepoint is for rollback. There is no limit to the number of savepoints. Savepoints and virtual In-machine snapshots are similar. A savepoint is a point in a transaction. Used to cancel part of the transaction. When the transaction ends, all save points defined in the transaction will be automatically deleted.

When executing rollback, you can roll back to the specified point by specifying a save point.

Several important operations for rolling back a transaction

1. Set the save point savepoint a

2. After canceling the save point a, the transaction rollback to a

3. Cancel all transaction rollback

Note: This rollback transaction must be used before commit;

public class UserRepository {
 
	
	private DataSource masterDataSource;
	private Connection connection = null;
	@Autowired
	public void setMasterDataSource(DataSource masterDataSource) {
		this.masterDataSource = masterDataSource;
	}
 
 
	@Transactional
	public boolean save(User user) {
		try {
			connection = masterDataSource.getConnection();
			connection.setAutoCommit(false);
			//设置保护点
			Savepoint saveUser = connection.setSavepoint("saveUser");
			PreparedStatement prepareStatement = connection.prepareStatement("insert into user(id,name,age) values(?,?,?)");
			prepareStatement.setLong(1, user.getId());
			prepareStatement.setString(2, user.getName());
			prepareStatement.setInt(3, user.getAge());
			prepareStatement.execute();
		
			try {
				update(user);
			} catch (Exception e) {
				System.out.println("出错了。。"+e);
				//回滚至保护点
				connection.rollback(saveUser);
			}
			connection.commit();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return true;
	}
	
	public boolean update(User user) {
		System.out.println("save user:"+user);
		
		try {
			PreparedStatement prepareStatement = connection.prepareStatement("update user set name = ? ,age = ? where id = ?)");
			prepareStatement.setLong(3, user.getId());
			prepareStatement.setString(1, "王大拿");
			prepareStatement.setInt(2, 100/0);
			prepareStatement.execute();
			
			connection.commit();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return true;
	}
}

Please correct me if there are any errors in the above content, thank you !

For more Mysql-related questions, please visit the PHP Chinese website: Mysql video tutorial

The above is the detailed content of Detailed introduction to SpringBoot transactions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete