Declarative transactions
Review of business
- Transactions are very important in the project development process. They involve the issue of data consistency and should not be careless!
- Transaction management is a necessary technology in enterprise application development to ensure data integrity and consistency.
A transaction is to treat a series of actions as an independent unit of work, either all of which are completed or all of which do not work.
The four attributes ACID principle of transaction
atomicity
Transactions are atomic operations, composed of a series of actions. The atomicity of the transaction ensures that the actions are either completed or not working at all.
consistency
Once all transaction actions are completed, the transaction is committed. Data and resources are in a consistent state that meets business rules
Isolation
It is possible that multiple transactions will process the same data at the same time, so each transaction should be isolated from other transactions to prevent data corruption.
durability
Once the transaction is completed, no matter what error occurs in the system, the result will not be affected. Normally, the result of the transaction is written to persistent memory
test
Copy the above code into a new project
In the previous case, we added two new methods to the userDao interface, deleting and increasing users;
//Add a userint addUser(User user); //Delete the user according to the idint deleteUser(int id);
We deliberately wrote deletes incorrectly and test!
<insert parameterType=""> insert into user (id,name,pwd) values (#{id},#{name},#{pwd}) </insert> <delete parameterType="int"> deletes from user where id = #{id} </delete>
Write an interface implementation class, and in the implementation class, we operate it for a while
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper { //Add some operations public List<User> selectUser() { User user = new User(4,"Xiao Ming","123456"); UserMapper mapper = getSqlSession().getMapper(); (user); (4); return (); } //Add new public int addUser(User user) { UserMapper mapper = getSqlSession().getMapper(); return (user); } //delete public int deleteUser(int id) { UserMapper mapper = getSqlSession().getMapper(); return (id); } }
test
@Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext(""); UserMapper mapper = (UserMapper) ("userDao"); List<User> user = (); (user); }
Error: SQL exception, delete is written incorrectly
Result: The insertion was successful!
There is no transaction management; we want them to succeed only if they succeed. If one fails, they all fail, and we should need transactions!
In the past, we all needed to manage our own affairs manually, which was very troublesome!
But Spring provides us with transaction management, and we only need configuration;
Transaction management in Spring
Spring defines an abstraction layer on top of different transaction management APIs, so that developers can use Spring's transaction management mechanism without having to understand the underlying transaction management API. Spring supports programmatic transaction management and declarative transaction management.
Programmatic transaction management
- Embed transaction management code into business methods to control transaction commit and rollback
- Disadvantages: Additional transaction management code must be included in each transaction operation business logic
Declarative transaction management
- Generally speaking, it is better than programming transactions.
- Separate transaction management code from business methods and implement transaction management in a declarative manner.
- Transaction management is regarded as a cross-cutting concern and modularize it through the AOP method. Declarative transaction management is supported through the Spring AOP framework in Spring.
Use Spring to manage transactions, pay attention to the constraint import of header files: tx
xmlns:tx="/schema/tx" /schema/tx /schema/tx/">
Transaction Manager
- Regardless of Spring's transaction management policy (programmed or declarative) transaction manager is required.
- It is Spring's core transaction management abstraction, and management encapsulates a set of technology-independent methods.
JDBC transactions
<bean class=""> <property name="dataSource" ref="dataSource" /> </bean>
After configuring the transaction manager, we need to configure the notification of transactions
<!--Configure transaction notifications--> <tx:advice transaction-manager="transactionManager"> <tx:attributes> <!--What methods to configure what transactions to use,Configure transaction propagation characteristics--> <tx:method name="add" propagation="REQUIRED"/> <tx:method name="delete" propagation="REQUIRED"/> <tx:method name="update" propagation="REQUIRED"/> <tx:method name="search*" propagation="REQUIRED"/> <tx:method name="get" read-only="true"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice>
Spring transaction propagation features:
Transaction propagation behavior is how transactions propagate between methods when multiple transaction methods are called to each other. Spring supports 7 transaction propagation behaviors:
- propagation_requierd: If there is no transaction at present, create a new transaction. If there is already a transaction, add it to this transaction. This is the most common choice.
- propagation_supports: Supports the current transaction. If there is no current transaction, it will be executed in a non-transactional method.
- propagation_mandatory: Use the current transaction, if there is no current transaction, an exception will be thrown.
- propagation_required_new: Create a new transaction. If the transaction currently exists, suspend the current transaction.
- propagation_not_supported: executes operations in a non-transactional manner, and if a transaction currently exists, the current transaction will be suspended.
- propagation_never: executes operations in a non-transactional manner, throws an exception if the current transaction exists.
- propagation_nested: If a transaction currently exists, it is executed within a nested transaction. If there is no transaction at present, perform an operation similar to propagation_required
Spring's default transaction propagation behavior is PROPAGATION_REQUIRED, which is suitable for most cases.
Assuming () all work in a transaction environment (that is, all enhanced by Spring transactions), assuming that there is the following call chain in the program: Service1.method1()->Service2.method2()->Service3.method3(), then the 3 methods of these 3 service classes work in the same transaction through Spring's transaction propagation mechanism.
For example, the methods we just now have calls, so they will be placed in a group of transactions!
Configure AOP
Import the header file of aop!
<!--ConfigurationaopWeaving into business--> <aop:config> <aop:pointcut expression="execution(* .*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config>
Perform a test
Delete the data you just inserted and test again!
@Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext(""); UserMapper mapper = (UserMapper) ("userDao"); List<User> user = (); (user); }
This is the end of this article about Spring's in-depth analysis of declarative transactions. For more relevant Spring declarative transaction content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!