Business Management>>>>Spring


1. Basic elements of business (ACID)

1.1 Atomicity

After the transaction starts, all operations are either done or not done. It is impossible to stop in the middle link. If an error occurs during the execution of the transaction, it will roll back to the state before the transaction started, and all operations will appear as if they did not happen. In other words, affairs are an indivisible whole, just like atoms learned in chemistry, they are the basic unit of matter.

1.2 Consistency

Before and after the transaction started, the integrity constraints of the database were not destroyed. For example, if A transfers money to B, it is impossible for A to deduct the money, but B does not receive it.

1.3 Isolation

At the same time, only one transaction is allowed to request the same data, and there is no interference between different transactions. For example, A is withdrawing money from a bank card, and B cannot transfer money to this card before A withdraws money.

1.4 Durability

After the transaction is completed, all updates made by the transaction to the database will be saved to the database and cannot be rolled back.


2. Transaction concurrency issues

2.1 Dirty reads

Transaction A reads the updated data of transaction B, and then B rolls back the operation, then the data read by A is dirty data.

Dirty reads occur when one transaction reads data that has been rewritten by another transaction but has not yet been committed. If the rewrite is rolled back later, the data obtained by the first transaction is invalid.

2.2 Nonrepeatable read

Transaction A reads the same data multiple times, and transaction B updates and commits the data in the process of multiple reads of transaction A. As a result, when transaction A reads the same data multiple times, the results are inconsistent.

Non-repeatable reads occur when a transaction executes the same query twice or more, but each time it gets different data. This is usually because another concurrent transaction was updated during the two queries.

2.3 Phantom read

User A changes the scores of all students in the database from specific scores to ABCDE grades, but user B inserts a record of specific scores at this time. After the modification of A is completed, it is found that there is still a record that has not been changed, it seems to happen It is the same as illusion, which is called phantom reading.

Phantom reading is similar to non-repeatable reading. It occurs when a transaction (T1) reads a few rows of data, and then another concurrent transaction (T2) inserts some data. In the subsequent query, the first transaction (T1) will find that there are more records that did not exist.


3. Isolation level of the transaction

3.1 Read uncommitted (ISOLATION_READ_UNCOMMITTED)

Read uncommitted: Even if the modification in the transaction is not committed, other transactions can still be seen, which will cause dirty reads, non-repeatable reads, and phantom reads.

3.2 Read has been submitted ((ISOLATION_READ_COMMITTED)

Read committed (Oracle database default isolation level): A transaction will not read data that has been modified but not committed by other parallel transactions. Avoid dirty reads, but will lead to non-repeatable reads, phantom reads.

3.3 Repeatable read (ISOLATION_REPEATABLE_READ)

Repeatable read (the default isolation level of Mysql database): A transaction will not read the modified and committed data of other parallel transactions (only when the transaction is committed will you see the modifications submitted by other transactions). Avoid dirty reads, non-repeatable reads, but will lead to phantom reads.

3.4 Serializable (ISOLATION_SERIALIZABLE)

Serializable: Transactions are executed serially, and only one transaction can be executed at a time. Avoid dirty reads, non-repeatable reads, and phantom reads.


4. Spring transaction control

  • The JavaEE system is developed hierarchically, and the transaction processing is located in the business layer. Spring provides a transaction processing solution with hierarchical design of the business layer.
  • The Spring framework provides us with a set of transaction control interfaces, which are in spring-tx-5.0.2.RELEASE.jar.
  • Spring's transaction control is based on AOP. It can be implemented either by configuration or by programming. It is recommended to use the configuration method.

4.1. API for transaction control in Spring

Spring does not directly manage transactions, but provides a variety of transaction managers. They delegate transaction management to the transactions of the relevant platform framework provided by persistence mechanisms such as Hibernate or JTA. Through the transaction manager PlatformTransactionManager, Spring provides corresponding transaction managers for various platforms such as JDBC, Hibernate, etc., but the specific implementation depends on the transaction implementation of their respective platforms.

PlatformTransactionManager interface: It is a transaction manager provided by Spring.
It provides the following methods for operating transactions:

	public interface PlatformTransactionManager {
    
    
	    TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;
	    void commit(TransactionStatus status) throws TransactionException;
	    void rollback(TransactionStatus status) throws TransactionException;
	}
  • TransactionStatus getTransaction(TransactionDefinition definition): Obtain transaction status information.
  • void commit(TransactionStatus status): Commit the transaction.
  • void rollback(TransactionStatus status): Roll back the transaction.

In actual development, we use the implementation class of the PlatformTransactionManager interface:

  • org.springframework.jdbc.datasource.DataSourceTransactionManager is used when using SpringJDBC or iBatis for persistent data.
  • org.springframework.orm.hibernate5.HibernateTransactionManager is used when the Hibernate version is used to persist data.

TransactionDefinition: Transaction Definition Information Object
It provides methods for querying transaction definitions:

  • String getName(): Get the name of the transaction object.
  • int getIsolationLevel(): Get the transaction isolation level and set the data visibility between two transactions.

From here we can see that the specific transaction management mechanism is transparent to Spring, so an advantage of Spring transaction management is to provide a consistent programming model for different transaction APIs, such as JTA, JDBC, Hibernate, etc.


4.2. Spring transaction definition and status description

It can be seen from the transaction manager PlatformTransactionManager that Spring needs two key elements to complete transaction management: transaction definition TransactionDefinition and transaction status TransactionStatus description.

	public interface TransactionDefinition {
    
    
	    int getPropagationBehavior(); //传播行为,默认PROPAGATION_REQUIRED
	    int getIsolationLevel();  //隔离级别,默认数据库默认级别,如mysql为可重复读
	    int getTimeout();
	    boolean isReadOnly();  //是否只读,查询操作可以设置为true
	    String getName();
	}

4.2.1. Transaction propagation behavior

There are two methods A and B that contain transactions. When B calls A, whether A starts a new transaction or continues B's transaction. This is the transaction propagation behavior. Spring provides 7 transaction propagation behaviors:

  • PROPAGATION_REQUIRED: The current method must be run in a transaction. If there is a current transaction, it will join the current transaction. Otherwise, a new transaction will be opened. Spring default behavior.
  • PROPAGATION_SUPPORTS: The current method does not require a transaction context. If there is a current transaction, join the current transaction, otherwise go streaking.
  • PROPAGATION_MANDATORY: The method must be run in a transaction, and an error will be reported if the current transaction does not exist.
  • PROPAGATION_REQUIRES_NEW: The method is running in its own new transaction.
  • PROPAGATION_NOT_SUPPORTED
  • PROPAGATION_NEVER
  • PROPAGATION_NESTED: The current transaction that already exists will run in a nested transaction, otherwise a new transaction will be started, involving savepoint.

4.2.2. Description of transaction status

public interface TransactionStatus extends SavepointManager {
    
    
    boolean isNewTransaction();  //是否新事务
    boolean hasSavepoint();  //是否有恢复点
    void setRollbackOnly();
    boolean isRollbackOnly();
    void flush(); //Flush the underlying session to the datastore, if applicable: for example, all affected Hibernate/JPA sessions.
    boolean isCompleted();
}

It can be seen that this interface describes some transaction processing methods that provide simple control of transaction execution and query transaction status. The transaction manager needs the corresponding TransactionStatus when it rolls back or commits.


5. Implementation of Spring Transaction

Programmatic transaction and declarative transaction are two spring transaction implementation methods:

  • Programmatic transactions can be implemented directly through PlatformTransactionManager, or simply through TransactionTemplate;
  • Declarative transactions can be implemented through xml configuration or @Transactional annotations.

5.1. Programmatic transaction implementation

spring configuration file jdbc-tx.xml


5.2. Declarative transaction implementation

5.2.1. xml configuration method to declare transactions

Spring configuration file: jdbc-tx-xml.xml, which is different from jdbc-tx.xml and adds aop transaction interception


5.2.2. Declaring transactions in annotations

Spring configuration file: jdbc-tx-anotation.xml, which is different from jdbc-tx.xml by adding package scanning and tx:annotation-driven


Guess you like

Origin blog.csdn.net/baidu_41847368/article/details/114528439