What is a transaction?

The so-called transaction refers to a group of operations in the database, which are either all successfully executed or all failed executed. The successful transaction is submitted to the database, and the failed transaction is rolled back.

Four characteristics of transactions

  • Atomicity

The atom is the smallest unit, representing indivisibility. Atomicity indicates that a transaction is the smallest unit of operations in a database and that all operations in a transaction either succeed or fail.

  • Consistency

The state of the database must be consistent before and after the transaction is executed.

  • Isolation

The execution of a transaction cannot be interfered with by another transaction, and the execution of a transaction is isolated from other transactions. That is, the data viewed by other transactions is either before or after a transaction is committed, and the intermediate process of transaction execution is isolated.

  • “Durability”

After a transaction is successfully committed, data changes caused by the actions of that transaction are persisted to the database.

Database read problems

Among the four characteristics of transaction, isolation is an important characteristic to ensure the security of transaction. If the isolation of transaction is not considered, it will cause the database read problem.

  • Dirty read: a transaction reads uncommitted data from another transaction. [Solution: Read submitted]
  • Non-repeatable read: one transaction reads update data that has been committed by another transaction, causing the data read by one transaction to be inconsistent with that read by the other two transactions. 【 Solution: Repeat 】
  • Phantom read: one transaction reads insert data that has been committed by another transaction, resulting in inconsistent results from multiple queries in one transaction. [Solution: Serialized read]

Isolation level of the database

To solve the database read problem, data isolation levels are set up.

  • Read uncommitted: No Read problem can be solved.
  • Read COMMITTED: The isolation level of a transaction. When a transaction is started, data cannot be Read until another transaction is committed. This can solve dirty reads, but non-repeatable reads and phantom reads can occur.
  • Repeatableread: isolation level of Repeatableread. In open transaction mode, update operation is not allowed for other transactions. This can solve dirty read and unrepeatable read, but phantom read may occur.
  • Serializable: Serializable read, all transactions are serialized and executed sequentially to solve all read problems. However, the isolation level of this transaction can significantly slow down database performance.

Spring transaction management

With this knowledge of transactions in hand, we are ready to take a look at Spring’s transaction management. In Spring, the PlatformTransactionManager manager interface is the transaction platform, is used for real management object in the Spring, it has two concrete implementation class, the underlying respectively using different ways of transaction management.

  • DataSourceTransactionManager: to use the underlying JDBC transaction management
  • HibernateTransactionManager: the underlying use Hibernate management affairs

Spring defines the propagation behavior of seven transactions in total

Keep multiple operations in the same transaction

  1. PROPAGATION_REQUIRED: Default, if A has A transaction, use the transaction in A, if A does not, create A new transaction to include the operation.
  2. PROPAGATION_SUPPORTS: Supports transactions, if there are transactions in A, use the transactions in A. If A does not have A transaction, do not use A transaction.
  3. PROPAGATION_MANDATORY: Use A transaction if there is one in A. If A has no transaction, an exception is thrown.

[Ensure multiple operations are not in the same transaction]

  1. PROPAGATION_REQUIRES_NEW: If A has A transaction, suspend (pause) A’s transaction and create A new one, containing only its own operations. If there are no transactions in A, create A new transaction with its own operations.
  2. 5, PROPAGATION_NOT_SUPPORTED: Suspends A’s transaction if A has A transaction. Do not use transaction management.
  3. PROPAGATION_NEVER: If A has A transaction, an exception is reported.

[Nested transaction]

  1. Execute A savepoint (B) if A transaction exists, PROPAGATION_NESTED: A transaction is executed, and the operation in B is executed. If no exception exists, the operation passes. If an exception exists, roll back to the initial location or to the savepoint.

Spring Programmatic Transaction Management (Understanding)

Spring programmatic transaction management, due to the large amount of code written, will hardly be used in formal development, this knowledge is limited to understanding.

<! Step 1: Configure the transaction manager in the Spring configuration file --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/> </bean> <! Step 2: Configure the transaction template in the Spring configuration file --> <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
</bean>
Copy the code
@Autowired
private UserDao userDao;

/** * Step 3 inject the transaction template */ in the service layer
@Autowired
private TransactionTemplate transactionTemplate;

@Override
public void deleteUser(Integer id) throws Exception {
	/** * step 4: Use the execute method in the transaction template, pass in an anonymous internal excuse, * and implement the method in the interface, putting all the code in this method */
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @SneakyThrows
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            userDao.deleteUser(id);
            int i = 1/0; }}); }Copy the code

Spring’s declarative transaction management

  • XML configuration file based approach
<! DataSource --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/> </bean> <! --> <tx:advice ID ="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <! Transaction propagation behavior, all save methods start with save, transaction propagation behavior is REQUIRED--> <tx:method name="save*" propagation="REQUIRED"/ > <! All delete methods start with delete, and the transaction propagation behavior is REQUIRED--> <tx:method name="delete*" propagation="REQUIRED"/ > <! All update methods start with update and transaction propagation behavior is REQUIRED--> <tx:method name="update*" propagation="REQUIRED"/ > <! All query methods start with find, transaction propagation behavior is SUPPORTS, transaction read-only --> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <! <aop:config> < AOP :pointcut id="pointcut" expression="execution(* com.hrp.service.impl.*.*(..) )"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
</aop:config>
Copy the code
  • Based on the @Transactional annotation
<! <tx:annotation-driven Transaction Manager ="transactionManager"/>
Copy the code
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
@Override
public void deleteUser(Integer id) throws Exception {
    userDao.deleteUser(id);
    int i = 1/0;
}
Copy the code

Transactional transaction management based on the @Transactional annotation can also be defined using attributes in the annotation.

  • RollbackFor :(bytecode object with an exception value) rolled back when this exception is encountered
  • NoRollbackFor :(bytecode object with an exception value) does not roll back when this exception is encountered
  • Propagation :(value is propagation enumeration object) propagation behavior of a transaction
  • ReadOnly :(true or false) whether the transaction is read-only

Spring transaction rollback rules: In Spring transaction management, by default transactions are rolled back only when run time exceptions are encountered, and not when compile-time exceptions are encountered. Of course, the developer can also specify that some kind of exception rollback is encountered or not.