Spring’s programmatic and declarative transactions
Entrance (understand some basic concepts)
Spring transaction properties (what are the properties of transactions?)
We all know that transactions have properties such as start, savepoint, commit, rollback and isolation level. What are spring's definitions of transaction attributes? Through the transactiondefinition interface, we can understand:
Get isolation level
Get propagation properties
Get timeout
Gets whether the is read-only
Transaction isolation level
Isolation and separation are also defined through the transactiondefinition interface, which represents the isolation degree of concurrent transactions.
*Transaction propagation behavior
The so-called transaction propagation behavior means that if a transaction context already exists before starting the current transaction, there are several options to specify the execution behavior of a transactional method. The definition of transaction finalization includes the following constants representing propagation behavior
*Transaction timeout
Specifies the maximum run time of the transaction. Use int to specify in seconds.
*Read only property of the transaction
The read-only attribute of a transaction refers to the read-only operation or read-write operation on transactional resources. The so-called transactional resources refer to those resources managed by transactions, such as data sources, JMS resources, custom transactional resources and so on. If we decide to only perform read-only operations on transactional resources, we can mark transactions as read-only to improve the performance of transaction processing. In transactiondefinition, boolean type is used to indicate whether the transaction is read-only.
*Rollback rules for transactions
By default, the runtimeException will be rolled back. If no exception is thrown, or a checked exception is thrown, the transaction is still committed. This is usually the way most developers want to handle it, and it is also the default way in EJBs. (the personal understanding here is that the checked exception is the checkedexception defined by us, including our custom exceptions and exceptions captured by calling methods)
Three basic classes of spring transactions
In the spring framework, there are about 100 APIs related to transaction management, of which three are the most important: transactiondefinition, platform transactionmanager and transactionstatus. The so-called transaction management is actually "performing commit or rollback operations according to given transaction rules". "Given transaction rule" is represented by transactiondefinition, "commit or rollback according to..." is represented by platform transactionmanager, and transactionstatus is used to represent the status of a running transaction. To make an inappropriate analogy, the relationship between transactiondefinition and transactionstatus is like the relationship between a program and a process.
Transactiondefinition defines the properties of a transaction
Transactionstatus defines the status of a transaction
Platform transaction manager is the implementation interface of various transaction platforms
Therefore, we can now go down. The real implementation of spring transactions is the implementation class of platformtransactionmanager, which meets the requirements of transactiondefinition and transactionstatus through various parameters. Finally, we conduct transaction management according to our programmed or declared.
According to the different underlying frameworks (let's look at the codes of datasourcetransactionmanager and Hibernate transaction manager later and what they do), the main implementations provided by spring (or other frameworks) are as follows:
Datasourcetransactionmanager: suitable for JDBC and ibatis
Hibernate transaction manager: suitable for hibernate
JPA transaction manager: applicable to data persistence operations using JPA (lower level)
It is applicable to data persistence using JPA
Now that the basic concept is finally over, we can introduce two types of transaction management
Programming transaction management
First, let's recall what hibernate transaction management is like when spring transaction management is not applicable? Maybe we manually get the session, get the transaction, start the transaction, commit or rollback, and close the session
After we use the management of spring, the transaction itself is still controlled by the persistence framework. Knowledge spring is like an agent. You tell it, and then it transforms and tells the underlying framework.
Take a practical example:
Programmable transaction management based on underlying API
Corresponding XML file:
But what is the difference between this way of writing and what we do not apply to spring? At most, the transaction level is raised to the service layer, not limited to the Dao layer, so spring has made improvements: programmatic transaction management based on transactiontemplate
The execute method of transactiontemplate provides an internal anonymous class to write transaction code, and then provides a parameter of transactionstatus, so that you can control rollback. In this way, we don't have to write any code about the transaction API. The format is probably Boolean B = transactiontempo Execute (New transactioncallback() {execute method (transactionstatus transactionstatus) {}}. When the execution is completed, a Boolean value is returned Another method is not to provide the returned results.
Corresponding XML:
From the results, it seems that it is not simple and clear enough. Now let's look at declarative transaction management, which is also a recommended method
Declarative transaction management
Spring's declarative transaction management is based on AOP, adding pointcuts before and after methods to open transactions and commit / rollback transactions.
Management based on transactioninterceptor
Initially, spring provided the transactioninterceptor class to implement declarative transaction management
Firstly, we configure a transactioninterceptor to define relevant transaction rules. It has two main attributes: one is transactionmanager, which is used to specify a transaction manager and delegate specific transaction related operations to it; The other is the transactionattributes attribute of properties type, which is mainly used to define transaction rules. In each key value pair of the attribute, the key specifies the method name, the method name can use wildcards, and the value represents the transaction attribute applied by the corresponding method.
There are complex rules for specifying the value of transaction attributes, which is a headache in spring. The specific writing rules are as follows:
Propagation behavior [, isolation level] [, read-only property] [, timeout property] [exceptions that do not affect submission] [, exceptions that cause rollback]
Declarative transaction management based on transactionproxy
Although the previous declarative transaction is good, there is a very annoying problem: too many configuration files.
To alleviate this problem, spring provides us with a transactionproxyfactorybean, which combines the configuration of transactioninterceptor and proxyfactorybean
In this way, the proxy code is reduced, but each service still needs a configuration. Therefore, we can use the configuration of automatic agent, which reduces a lot of configuration. It should also be the most commonly used.
Namespace based declarative transaction management
The first two declarative transaction configuration methods lay the foundation of spring declarative transaction management. On this basis, spring 2 X introduces namespaces and uses namespaces in combination, which gives developers a new experience in configuring declarative transactions, and the configuration becomes simpler and more flexible. In addition, declarative transactions have become more powerful thanks to the pointcut expression support of namespaces.
Specific examples:
@Declarative transaction management of transactional
In addition to the namespace based transaction configuration, spring 2 X also introduces annotation based annotation, which mainly involves @ transactional annotation@ Transactional can act on interfaces, interface methods, classes, and class methods. When acting on a class, all public methods of the class will have transaction attributes of this type. At the same time, we can also use this annotation at the method level to override the class level definition.
Specific examples:
However, to use this method, we must enable TX annotation:
appendix
Datasourcetransactionmanager (the main method of the class, not the original code)
Set and get datasource
Get transaction
Does the transaction exist
Start transaction
Pause, release connection
Resume suspended connections
Submit
RollBACK
Rollback only
clear
…
HibernateTransactionManager
Conversion exception
Start transaction
clear
Submit
Get transaction
recovery
RollBACK
Rollback only
suspend
Get data source
Get interceptor of entity
Get sessionfactory
Is there a transaction
Pre submission
Summary @ h_ 185_ 419@
That's all for the detailed introduction of spring's programmatic transactions and declarative transactions. I hope it will be helpful to you. If you have any questions, you can leave a message at any time. Xiaobian will reply to you in time. Thank you very much for your support!