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

Probably the most beautiful detail on Spring transaction management

Review of Transaction concepts

What is a transaction?

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

Properties of things (ACID) :

  1. Atomicity: Transactions are the smallest unit of execution and do not allow splitting. The atomicity of the transaction ensures that the action either completes completely or does not work at all;
  2. Consistency: Data is consistent before and after a transaction is executed.
  3. Isolation: when accessing the database concurrently, a user’s things are not disturbed by other things, and the database is independent between the concurrent transactions.
  4. Persistence: After a transaction is committed. Its changes to the data in the database are persistent and should not be affected if the database 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 rule)
  • TransactionStatus: Transaction running status

    Transaction management is simply “performing commit or rollback operations according to a given transaction rule”.

PlatformTransactionManager interface is introduced

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

PlatformTransactionManager interface code is as follows:

PlatformTransactionManager interface defines three methods:

Public interface PlatformTransactionManager()... { // Return a currently active transaction or create a new one, To return to the current transaction or to create a new transaction according to the specified propagation behavior. TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; // Commit the given transaction, Void commit(TransactionStatus Status) throws TransactionException; // Perform a rollback of the given transaction Void rollback(TransactionStatus status) throws Perform a rollback of the given transaction 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 (Mybatis) for data persistence, our XML configuration is usually as follows:

<! - the transaction manager - > < bean id = "transactionManager" class = ". Org. Springframework. JDBC datasource. DataSourceTransactionManager "> <! DataSource ="dataSource" /> </ dataSource >Copy the code

TransactionDefinition Interface description

The transaction manager interface PlatformTransactionManager through getTransaction (TransactionDefinition definition) method to get a transaction, The parameters in this method are 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, describing how transaction policies are applied to methods. The transaction attribute contains five aspects.

The methods in the TransactionDefinition interface are as follows:

There are five methods defined in the TransactionDefinition interface along with constants representing transaction properties such as isolation level, propagation behavior, and so on.

I have listed the methods in the TransactionDefinition interface below, not the constants defined in the interface, which will be described later.

Public interface TransactionDefinition {// Return the transaction propagationBehavior (); Int getIsolationLevel(); int getIsolationLevel(); int getIsolationLevel(); // Returns the transaction name String getName(); int getTimeout(); // Returns whether to optimize for a read-only transaction. boolean isReadOnly(); }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 associated with concurrent transactions and then look at the five constants that represent the isolation level defined in the TransactionDefinition interface.

Problems with concurrent transactions

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

  • Dirty read: When a transaction is accessing data and making changes to the data that have not been committed to the database, another transaction also accesses the data and then consumes it. Because this data is not committed yet, another transaction reads this data as “dirty data” and may not be doing the right thing based on “dirty data”.
  • Lost to modify: When a transaction reads data that is also accessed by another transaction, the first transaction changes the data and the second transaction changes the data. The result of the modification within the first transaction is then lost and is therefore called a lost modification.

For example, transaction 1 reads A table A=20, transaction 2 also reads A=20, transaction 1 changes A=A-1, transaction 2 also changes A=A-1, the final result A=19, the modification of transaction 1 is lost.

  • Unrepeatableread: Reads the same data multiple times within a transaction. While this transaction is not finished, another transaction also accesses the data. Then, between the two reads in the first transaction, the data read by the first transaction may not be the same because of modifications made by the second transaction. This occurs when the data read twice within a transaction is not the same and is therefore called a non-repeatable read.
  • Phantom read: Phantom read is similar to unrepeatable reading. It occurs when one transaction (T1) reads several rows of data, followed by another concurrent transaction (T2) inserts some data. In subsequent queries, the first transaction (T1) will find more records that did not exist before, as if an illusion occurred, so it is called phantom read.

Non-repeatability and illusory difference:

Unrepeatable read focus is modified, magic read focus is added or deleted.

Example 1: Before Mr. A in transaction 1 reads his salary as 1000, Mr. B in transaction 2 changes A’s salary to 2000, which causes A to read his salary as 2000. This is unrepeatable reading.

Example 2 (under the same conditions, the number of records read on the first and second time is different) : There are 4 people whose salary is more than 3000 in a payroll table. Transaction 1 reads all the people whose salary is more than 3000 and checks 4 records in total. At this time, transaction 2 inserts another record whose salary is more than 3000 and checks 5 records when transaction 1 reads again.

Isolation level

Five constants representing the isolation level are defined in the TransactionDefinition interface:

  • 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 by one so that interference between transactions is completely impossible. That is, this level prevents dirty reads, unrepeatable reads, and phantom reads. But this severely affects the performance of the program. This level is also not typically used.

Is not feeling brain cells enough to use, Hashimoto Nai nai did not understand ~~~ appearance level against heaven good!!

(2) Transaction propagation behavior (in order 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. TransactionDefinition includes the following constants that represent propagation behavior:

Cases that support the current transaction:

  • TransactionDefinition. PROPAGATION_REQUIRED: if a transaction exists, then join the transaction; If there is no transaction currently, a new transaction is created.
  • TransactionDefinition. PROPAGATION_SUPPORTS: if a transaction exists, then join the transaction; If there is no transaction currently, it continues in a non-transactional manner.
  • TransactionDefinition. PROPAGATION_MANDATORY: if a transaction exists, then join the transaction; If there is no transaction currently, an exception is thrown.

The current transaction is 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 information:

  • 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 is important to point out that the previous six transaction propagation behaviors were introduced by Spring from EJBs and share the same concept. PROPAGATION_NESTED is unique to Spring. A nested transaction is not an independent transaction (if any), depending on the existence of an external transaction. An internal transaction can be committed only by an external transaction, and nested subtransactions cannot be committed independently. Nested transactions are easy to understand if you are familiar with the concept of savepoints in JDBC. A nested subtransaction is an application of savepoints. A transaction can contain multiple savepoints, each nested subtransaction. In addition, rollback of an external transaction also results in rollback of nested child transactions.

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

A transaction timeout is the maximum time that a transaction is allowed to execute, and if the transaction has not completed after this time, the transaction is automatically rolled back. The timeout period in TransactionDefinition is represented by an int in seconds.

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

The read-only property of a transaction refers to read-only or read-write operations on transactional resources. Transactional resources are those managed by transactions, such as data sources, JMS resources, custom transactional resources, and so on. If it is determined that only transactional resources will be read-only, we can mark the transaction as read-only to improve transaction processing performance. A Boolean type is used in TransactionDefinition to indicate whether the transaction is read-only.

(5) Rollback rules (define transaction rollback rules)

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

TransactionStatus Describes the TransactionStatus interface

The TransactionStatus interface is used to record the status of a transaction. This interface defines a set of methods for obtaining or determining the status 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 in the current call stack).

TransactionStatus Interface The content of this interface is as follows:

public interface TransactionStatus{ boolean isNewTransaction(); HasSavepoint (); Void setRollbackOnly(); // Set to rollback only Boolean isRollbackOnly(); // Whether only Boolean isCompleted is rolled back; }}Copy the code

Due to space constraints, I will introduce Spring programming and declarative transactions through a transfer example in the next article.

“Java Interview Clearance Manual”