Development tools and key technologies: Java
Author: Xiao guangbin
Written on: June 6, 2021
What is business?
Transaction generally refers to what is to be done or done. Transaction is an operation sequence of accessing database. Database application system accesses database through transaction set. The correct execution of transactions makes the database transition from one state to another.
Why use transactions?
Transaction is proposed to solve the problem of data security operation. Transaction control is actually to control the secure access of data.
Take a simple example: Alipay transfer business, A account to B account 200, A account less 200, B account to add 200, if the transfer process in the network error, A account less 200, and B account did not add 200 pieces, then this business is operation failure, then we have to control it, can not B account did not receive the account transfer account A. Account a is short of money. A account transfer business is cancelled. This can ensure the correctness of the business. Put the decrease of account a's funds and the increase of account B's funds into the same transaction, and either all of them will be executed successfully or revoked, so as to ensure the security of data. In short, the transfer is either successful or failed together.
Four characteristics of transaction (ACID):
1. atomicity: it means that any failure in the transaction execution process will invalidate any modification made by the transaction, that is, either all or no execution.
2. consistency: when the transaction fails, all data affected by the transaction should be restored to the state before the transaction is executed.
3. isolation: the execution of a transaction cannot be affected by other transactions.
4. durability: it means that the submitted data should be in the correct state when the transaction fails.
There are three types of Java transactions: JDBC transactions, JTA (Java Transaction API) transactions, and container transactions.
Possible problems caused by concurrent transaction processing:
1. dirty read: one transaction reads the uncommitted data of another transaction.
2. Non repeatable read: the operation of one transaction causes another transaction to read different data twice before and after.
3. phantom read: the operation of one transaction results in different amount of data in the results of two queries before and after another transaction.
Example 1: when A and B transactions execute concurrently, after A transaction is modified, B transaction reads the uncommitted data of A transaction. At this time, A data has been rolled back, then B transaction reads the invalid "dirty" data of A transaction.
Example 2: after transaction a reads the data, transaction B modifies the data read by transaction A. at this time, transaction a reads the data again and finds that the two data are different.
Example 3: after transaction a queries the data, transaction B adds or deletes a piece of data that meets the query of transaction A. at this time, transaction a queries the data and finds that the data record does not exist before or the previous data record does not exist.
Seven propagation behaviors of transactions:
1,PROPAGATION_REQUIRED: if there is no transaction at present, create a new transaction. If there is already a transaction, join it. This is the default transaction propagation behavior.
2,PROPAGATION_SUPPORTS: supports the current transaction. If there is no transaction, it will be executed in a non transaction manner.
3,PROPAGATION_MANDATORY: supports the current transaction. If there is no transaction, an exception will be thrown.
4,PROPAGATION_REQUIRES_NEW: create a new transaction. If there is a current transaction, postpone the current transaction.
5,PROPAGATION_NOT_SUPPORTED: the operation is performed in a non transactional manner. If there is a current transaction, the current transaction will be suspended.
6,PROPAGATION_NEVER: execute in a non transactional manner. If there is a transaction currently, an exception will be thrown.
7,PROPAGATION_NESTED: if not, create a new transaction; If so, nest other transactions in the current transaction.
Isolation level of transaction:
1,ISOLATION_DEFAULT: This is the default isolation level of PlatfromTransactionManager. The default transaction isolation level of the database is used.
2,ISOLATION_READ_UNCOMMITTED: This is the lowest isolation level of a transaction. It allows another transaction to see the uncommitted data of this transaction. This isolation level produces dirty reads, non repeatable reads, and phantom reads.
3,ISOLATION_READ_COMMITTED: ensure that the modified data of one transaction can be read by another transaction only after it is committed. Another transaction cannot read the uncommitted data of the transaction. This transaction isolation level can avoid dirty reads, but non repeatable reads and phantom reads may occur.
4,ISOLATION_REPEATABLE_READ: this transaction isolation level can prevent dirty reads and cannot be read repeatedly. But there may be unreal reading. In addition to ensuring that one transaction cannot read the uncommitted data of another transaction, it also ensures that it cannot be read repeatedly.
5,ISOLATION_SERIALIZABLE: This is the most expensive but most reliable level of transaction isolation. Transactions are processed in order. In addition to preventing dirty reading and non repeatable reading, it also avoids illusory reading.
JDBC transactions are used here. Before using transactions in the project, we need to configure some necessary configuration files, which is in spring mybatis There is also a configuration using annotation transactions configured in XML. Depending on personal needs, it is not configured here
<!-- transaction management --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- use annotation Define transaction --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
Start the transaction in the controller's method
@ResponseBody @RequestMapping(value = "/addStudents", produces = "application/json; charset=utf-8") public JsonReturn addStudents(Students students,HttpServletRequest request)throws Exception{ JsonReturn jsonReturn = new JsonReturn(); AccountantRecord accountantRecord = new AccountantRecord(); //Get the object of Spring container WebApplicationContext contextLoader = ContextLoader.getCurrentWebApplicationContext(); //Set default properties for properties DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); //Set the propagation behavior of a transaction. Here, it is set to start a new transaction definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); //Set the isolation level of the transaction. Here is read committed definition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); //Get the DataSourceTransactionManager from the spring container object, which is based on the id name (transactionManager) configured in the configuration file DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) contextLoader.getBean("transactionManager"); //Get transaction status object TransactionStatus transactionStatus = (TransactionStatus) transactionManager.getTransaction(definition); try { //Method to execute int intS = StudentsMapper.addStudents(students); if (intS>0){ StudentsMapper.addAccountantRecord(accountantRecord);//Add a second table } //Commit transaction transactionManager.commit(transactionStatus); }catch (Exception e){ //Rollback transaction transactionManager.rollback(transactionStatus); jsonReturn.setMsg("operation failed"); } return jsonReturn; }
If an exception occurs to the newly added table after the transaction is started, the transaction will be rolled back, as shown in the following figure:
The above is sorted out by personal understanding + combined data. If there is any error, please correct it!!!