Java Interview Guide (Java Study Guide) : github.com/Snailclimb/…

Perhaps the most beautiful Spring transaction management detail

Review of Transaction Concepts

What is a transaction?

A transaction is a logical set of operations that either all or none of them are executed.

The quality (ACID) of something:

  1. Atomicity: the transaction is the smallest unit of execution and does not allow splitting. The atomicity of the transaction ensures that the action is either complete or not effective at all;
  2. Consistency: Data remains consistent before and after transaction execution;
  3. Isolation: concurrent access to the database, a user’s business is not disturbed by other things, the database is independent between concurrent transactions;
  4. Persistence: after a transaction has been committed. Its changes to the data in the database are persistent and should not have any impact on the database even if it fails.

Introduction to Spring transaction Management interface

Spring Transaction Management Interface:

  • The transaction manager PlatformTransactionManager: (platform)
  • TransactionDefinition: TransactionDefinition information (transaction isolation level, propagation behavior, timeout, read-only, rollback rules)
  • TransactionStatus: transaction running status

Transaction management is “commit or roll back operations according to the given transaction rules”.

PlatformTransactionManager interface is introduced

Spring does not directly manage transactions, but instead provides a variety of transaction managers that delegate their responsibility to the transactions of the relevant platform framework provided by a persistence mechanism such as Hibernate or JTA. The Spring transaction Manager interface is: Org. Springframework. Transaction. The PlatformTransactionManager, through this interface, the Spring for each platform such as JDBC, Hibernate provides corresponding transaction manager, But the specific implementation is up to each platform.

PlatformTransactionManager interface code is as follows:

PlatformTransactionManager interface defines three methods:

Public interface PlatformTransactionManager(a).{  
    // Return a currently active transaction or create a new one, according to the propagation behavior of the specified Returns the currently active transaction or creates a new transaction.
    TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; 
    Commit the given transaction, with regard to its status
    Void commit(TransactionStatus status) throws TransactionException;  
    // Perform a rollback of the given transaction
    Void rollback(TransactionStatus status) throws TransactionException;  
    } 
Copy the code

We just also said that the Spring in the PlatformTransactionManager according to different persistence layer framework of the interface implementation class, a few more common as shown in the figure below

For example, when we use JDBC or iBatis (i.e. Mybatis) for data persistence, our XML configuration is usually as follows:

	<! -- Transaction Manager -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<! -- Data source -->
		<property name="dataSource" ref="dataSource" />
	</bean>
Copy the code

TransactionDefinition Describes the interface

The transaction manager interface PlatformTransactionManager through getTransaction (TransactionDefinition definition) method to get a transaction, The argument in this method is the TransactionDefinition class, which defines some of the basic transaction properties.

So what are transaction attributes?

Transaction attributes can be understood as some basic configuration of a transaction and describe how the transaction strategy is applied to a method. The transaction attribute contains five aspects.

The methods in the TransactionDefinition interface are as follows:

The TransactionDefinition interface defines five methods, as well as constants that represent transaction attributes such as isolation level, propagation behavior, and so on.

I’m only listing the methods in the TransactionDefinition interface and not the constants defined in the interface, which will be covered later.

public interface TransactionDefinition {
    // Return the propagation behavior of the transaction
    int getPropagationBehavior(a); 
    // Returns the isolation level of a transaction, which allows the transaction manager to control what data another transaction can see within this transaction
    int getIsolationLevel(a); 
    // Returns how many seconds the transaction must complete in
    // Return the name of the transaction
    String getName(a);int getTimeout(a);  
    // Returns whether to optimize for read-only transactions.
    boolean isReadOnly(a);
} 
Copy the code

(1) Transaction isolation level (which defines the extent to which a transaction may be affected by other concurrent transactions) :

Let’s take a look at the problems posed by concurrent transactions, and then look at the five constants defined in the TransactionDefinition interface that represent isolation levels.

Problems caused by concurrent transactions

In a typical application, multiple transactions run concurrently, often working on the same data to complete their respective tasks (multiple users working on the same data). Concurrency, while necessary, can lead to the following problems.

  • Dirty read: When a transaction accesses data and makes changes that have not yet been committed to the database, another transaction accesses the data and then uses the data. Because this data is uncommitted data, the data read by another transaction is “dirty data,” based on which the operation may not be correct.

  • Lost to Modify: When one transaction reads data that is accessed by another transaction, the first transaction changes the data and the second transaction changes the data. The result of the change within the first transaction is thus lost and is therefore called a lost change.

    For example, transaction 1 reads A=20, transaction 2 reads A=20, transaction 1 changes A=A-1, transaction 2 changes A= a-1, and transaction 1 changes A=A-1. The final result is A=19, and the change in transaction 1 is lost.

  • Unrepeatableread: indicates that the same data is read repeatedly in a transaction. The data is accessed by another transaction before the transaction ends. Then, between the two reads in the first transaction, the data read in the first transaction may not be quite the same because of the second transaction’s modification. This occurs when the data read twice within a transaction is different and is therefore called non-repeatable reads.

  • Phantom read: Phantom reads are similar to non-repeatable reads. It occurs when a transaction (T1) reads a few rows of data and then another concurrent transaction (T2) inserts some data. In subsequent queries, the first transaction (T1) will find more records that do not exist, as if hallucinating, so it is called a phantom read.

Non-repeatability and illusion difference:

The focus of non-repeatable read is modification, while the focus of magic read is adding or deleting.

Example 1: Before Mr. A (transaction 1) reads his salary (1000), Mr. B (transaction 2) changes A’s salary (2000), causing A to read his salary (2000). This is called non-repeatable reading.

Example 2 (same condition, the number of notes read in the first and second time is different) : In a payroll table, there are 4 people whose salary is greater than 3000, transaction 1 reads all the people whose salary is greater than 3000, and a total of 4 records are found. At this time, transaction 2 inserts another record whose salary is greater than 3000. When transaction 1 reads again, the number of records found becomes 5, which leads to phantom reading.

Isolation level

The TransactionDefinition interface defines five constants that represent isolation levels:

  • TransactionDefinition. ISOLATION_DEFAULT: use a backend database default isolation level, Mysql default REPEATABLE_READ isolation level used Oracle READ_COMMITTED) isolation level used by default.
  • TransactionDefinition. ISOLATION_READ_UNCOMMITTED: the lowest isolation level, allowing the read has not yet been submitted data changes, may lead to dirty reads, phantom read or not repeatable read
  • TransactionDefinition. ISOLATION_READ_COMMITTED: allow read of concurrent transactions have to submit data, can prevent dirty reads, but phantom read or not repeatable read could still happen
  • TransactionDefinition. ISOLATION_REPEATABLE_READ: many of the same field to read the results are consistent, unless the data have been modified by itself affairs on their own, can prevent the dirty read and not repeatable read, but phantom read could still happen.
  • TransactionDefinition. ISOLATION_SERIALIZABLE: the highest isolation level, completely obey the ACID isolation level. All transactions are executed one at a time so that interference between transactions is completely impossible, that is, this level prevents dirty reads, non-repeatable reads, and phantom reads. However, this can seriously affect the performance of the program. This level is not usually used.

Feel brain cells are not enough to use, Hashimoto Nai Nai did not understand ~~~ appearance level retrograde good!!

(2) Transaction propagation behavior (to solve the transaction problem of calling each other between business layer methods) :

When a transaction method is called by another transaction method, you must specify how the transaction should propagate. For example, a method may continue to run in an existing transaction, or it may start a new transaction and run in its own transaction. The following constants are included in the TransactionDefinition definition to indicate propagation behavior:

The current transaction is supported:

  • TransactionDefinition. PROPAGATION_REQUIRED: if a transaction exists, then join the transaction; If there is no current transaction, a new one is created.
  • TransactionDefinition. PROPAGATION_SUPPORTS: if a transaction exists, then join the transaction; If there are no current transactions, the run continues in a non-transactional manner.
  • TransactionDefinition. PROPAGATION_MANDATORY: if a transaction exists, then join the transaction; If there is no current transaction, an exception is thrown. (Mandatory)

Current transaction not supported:

  • TransactionDefinition. PROPAGATION_REQUIRES_NEW: create a new transaction, if a transaction exists, suspending the current transaction.
  • TransactionDefinition. PROPAGATION_NOT_SUPPORTED: run way of transaction, if a transaction exists, suspending the current transaction.
  • TransactionDefinition. PROPAGATION_NEVER: run way of transaction, if the current transaction, throw an exception.

Other situations:

  • TransactionDefinition. PROPAGATION_NESTED: if a transaction exists, then create a transaction for the current affairs of nested transactions to run; If no current affairs, the value of equivalent to the TransactionDefinition. PROPAGATION_REQUIRED.

It should be noted here that the previous six transaction propagation behaviors were introduced from EJBs by Spring, and they share the same concepts. PROPAGATION_NESTED is unique to Spring. If a nested transaction is nested within an external transaction (if one exists), the nested transaction is not a separate transaction, it is dependent on the existence of an external transaction, and only a commit from an external transaction can cause a commit from an internal transaction. Nested subtransactions cannot commit independently. If you are familiar with the concept of SavePoint in JDBC, then nested transactions are easy to understand. In fact, nested subtransactions are an application of SavePoint. A transaction can contain multiple savepoints, each nested subtransaction. In addition, a rollback of an external transaction also results in a rollback of nested subtransactions.

(3) Transaction timeout attribute (the maximum time a transaction is allowed to execute)

Transaction timeout refers to the maximum time that a transaction is allowed to execute. If the time limit is exceeded but the transaction has not completed, the transaction is automatically rolled back. The timeout is represented in the TransactionDefinition as an int value in seconds.

(4) Transaction read-only attribute (whether to perform read-only operations on transaction resources)

The read-only attribute of a transaction means that a transactional resource can be operated read-only or read or write. Transactional resources are those that are managed by transactions, such as data sources, JMS resources, and custom transactional resources. If it is determined that only the transactional resource is read-only, then we can flag the transaction as read-only to improve transaction performance. The Boolean type in the TransactionDefinition indicates whether the transaction is read-only.

(5) Rollback rules (define transaction rollback rules)

These rules define which exceptions cause a transaction to roll back and which do not. By default, transactions are rolled back only when they encounter run-time exceptions and not when they encounter check exceptions (this behavior is consistent with EJB rollback behavior). But you can declare that a transaction will be rolled back when it encounters a particular checked exception just as it would if it encountered a run-time exception. Also, you can declare that a transaction will not be rolled back if it encounters certain exceptions, even if those exceptions are runtime exceptions.

TransactionStatus Describes the interface

The TransactionStatus interface is used to record the state of a transaction. This interface defines a set of methods to obtain or determine the corresponding state information of a transaction.

PlatformTransactionManager. GetTransaction (…). Method returns a TransactionStatus object. The returned TransactionStatus object may represent a new or existing transaction (if there is a qualifying transaction on the current call stack).

TransactionStatus Interface The interface content is as follows:

public interface TransactionStatus{
    boolean isNewTransaction(a); // Is it something new
    boolean hasSavepoint(a); // Whether there is a recovery point
    void setRollbackOnly(a);  // Set it to rollback only
    boolean isRollbackOnly(a); // Whether to roll back only
    boolean isCompleted; // Whether it has been completed
} 
Copy the code

Because space is limited, I’ll introduce Spring programming and declarative transactions in my next article with a transfer example.

Welcome to follow my wechat official account: “Java Interview Clearance Manual “(a warm wechat official account, looking forward to making progress with you ~~~ adhere to the original, share beautiful articles, share a variety of Java learning resources) :