Article go to http://zhou137520.iteye.com/blog/1675199
Spring's solution to transactions is actually divided into 2 kinds: Programmatic implementation transactions, AOP configuration declarative Solutions. http://jinnianshilongnian.iteye.com/blog/1496953
Spring provides a number of built-in transaction manager implementations that are commonly used in the following ways:
Datasourcetransactionmanager: In the Org.springframework.jdbc.datasource package, the data source transaction Manager provides management of a single javax.sql.DataSource transaction for spring JDBC Abstract Framework, Ibatis framework of transaction management; Hibernatetransactionmanager: In Org.springframework.orm.hibernate3 or HIBERNATE4 packages, provides support for a single org.hibernate.SessionFactory transaction for integration Hibernate the transaction management of the framework, the transaction manager only supports the hibernate3+ version, and the spring3.0+ version only supports the Hibernate 3.2+ version; Jtatransactionmanager: In the ORG.SPRINGFRAMEWORK.TRANSACTION.JTA package, provides support for distributed transaction management and delegates transaction management to the Java EE Application Server transaction manager; Spring not only provides these transaction managers, but also provides a manager for such as JMS transaction management
Two open source JTA transaction implementation components that do not depend on the application server: Jotm and Atomikos transactions Essentials
Specific usage Reference http://jinnianshilongnian.iteye.com/blog/1439900
This blog explains how to implement and use Transactiontemplate for JDBC and JTA, respectively, for programmatic transaction management with Platformtransactionmanager: http:// jinnianshilongnian.iteye.com/blog/1441271
Programmatic implementation of transactions
Spring offers two programmatic transaction support: Directly using Platformtransactionmanager implementations and using the Transactiontemplate template class to support logical transaction management.
Transactiontemplate template classes are recommended if you are using programmatic transactions.
The core of the Spring Framework support transaction management is the transaction manager abstraction, which supports the transaction management of various data access frameworks for different data access frameworks (such as Hibernate) through the implementation of policy interface Platformtransactionmanager, The Platformtransactionmanager interface is defined as follows:
Public interface Platformtransactionmanager {
//Returns a transaction that has been activated or creates a new transaction
Transactionstatus Gettransaction ( Transactiondefinition definition)
throws transactionexception;
void commit (Transactionstatus status) throws TransactionException;
void rollback (Transactionstatus status) throws TransactionException;
}
About Transactiondefinition interfaces and Transactionstatus interfaces:
http://jinnianshilongnian.iteye.com/blog/1439900
Spring-Declarative Transactions
In daily development, the most used is declarative transactions, and the following is a description of how Springjdbc's declarative transactions are configured:
<context:component-scan base-package= "Com.chou.spring.jdbc"/> <!--configuration data source--> <bean id= "DataSource" CLA ss= "Com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method= "Close" > <!--Connection Info--> < Property Name= "Driverclass" value= "${db.driverclass}"/> <property name= "Jdbcurl" value= "${db.url}"/> < Property name= "User" value= "${db.username}"/> <property name= "password" value= "${db.password}"/> <!--C onnection pooling Info--> <property name= "Initialpoolsize" value= "1"/> <property name= "MinPoolSize" value= "1"/> <property name= "maxpoolsize" value= ""/> "<property" name= "MaxIdleTime" value= "1800"/> Rty name= "maxstatements" value= "0"/> </bean> <bean id= "Jdbctemplatedao" class= " Com.chou.spring.jdbc.dao.JdbcTemplateDao "> <property name=" dataSource "ref=" DataSource "/> </bean> & lt;! --JDBC transaction manager--> <bean id= "Jdbcttxmanager class=" org.springFramework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/>" </bean> <tx:advice id= "Txadvice" transaction-manager= "Jdbcttxmanager" > <tx:attributes> <tx: Method Name= "domain*"/> </tx:attributes> </tx:advice> <aop:config proxy-target-class= "true" > & Lt;aop:advisor advice-ref= "Txadvice" pointcut= "Execution (* com.chou.spring.jdbc.service.jdbctemplateservice.* (..))"
/> </aop:config>
public class Jdbctemplatedao extends jdbcdaosupport{public
void Save () {
String insertsql = ' INSERT INTO Tab_item VALUES (?,?,?) ";
Assert.istrue (Getjdbctemplate (). Update (Insertsql, new object[]{6, "HP", "PT540"}) = = 1, "Insert Failed")
;
public void Delete () {
String deletesql = "Delete tab_item where id =?";
Assert.istrue (Getjdbctemplate (). Update (Deletesql, new object[]{6}) = = 1, "delete failed")
;
public void Update () {
String updatesql = "Update tab_item set ItemNo =?, ItemName =? WHERE id =? ";
Assert.istrue (Getjdbctemplate (). Update (Updatesql, new object[]{"HP", "PT555", 6}) = = 1, "Modify failed");
}
/**
* *
@author Chou
* @since 2012-9-9
* The transaction is defined at the service level to avoid an error: * All calls to this method
via proxy Would be routed directly to the proxy.
* This is a transaction transfer problem, if you join the transaction in the control layer will not be prompted, and no warning,
* A lot of people in the final DAO to join the business there is a warning,
If the profile defines an AOP fetch proxy object that is proxy-target-class= "true" that is cglib
* and Cglib dynamic proxies are loaded into the class file of the proxy object class using the ASM Open source package,
* By modifying its bytecode to generate subclasses and inheriting the classes you write, and then adding things to manage on your basis,
* and the Setdatasource in Jdbcdaosupport is final he can't inherit * of
course you can ignore it and there's no problem.
* *
@Service public
class Jdbctemplateservice {
@Autowired
private Jdbctemplatedao Jdbctemplatedao;
public void domain () {
jdbctemplatedao.save ();
int i = 2/0;//here is a mistake, the transaction rolls back and the previous save is invalid
jdbctemplatedao.update ();
Jdbctemplatedao.delete ();
}
Main method
string[] configlocations = new string[] {"Applicationcontext.xml"};
ApplicationContext CTX = new Classpathxmlapplicationcontext (configlocations);
Jdbctemplateservice j = Ctx.getbean (Jdbctemplateservice.class);
J.domain ();
<tx:advice/> Configuration Detailed
<tx:advice id= "..." transaction-manager= "..." > <tx:attributes> <tx:method name= "*"
propagation= "REQUIRED" isolation= "DEFAULT" timeout= "-1" Read-only= "true" no-rollback-for= "" Rollbac K-for= "Java.lang.Exception"/> </tx:attributes> </tx:advice> <!--most commonly used configuration--> <tx:advice id= "TX Advice "transaction-manager=" Txmanager "> <tx:attributes> <tx:method name=" save* "propagation=" Requi RED "/> <tx:method name=" add* propagation= "REQUIRED"/> <tx:method "name=" create* gation= "REQUIRED"/> <tx:method name= "insert*" propagation= "REQUIRED"/> <tx:method name = "update*" propagation= "REQUIRED"/> <tx:method name= "merge*" propagation= "REQUIRED"/> ; Tx:method name= "del*" propagation= "REQUIRED"/> <tx:method name= "remove*" propagation= "REQUIRED"/> Name= "put*" propagation= "REQUIRED"/> <tx:method name= "get*" propagation= "SUPPORTS" read-only= "true"/>
; <tx:method name= "count*" propagation= "SUPPORTS" read-only= "true"/> <tx:method "name=" find*
N= "SUPPORTS" read-only= "true"/> <tx:method name= "list*" propagation= "SUPPORTS" read-only= "true"/> <tx:method name= "*" propagation= "SUPPORTS" read-only= "true"/> <tx:method name= "Batchsaveorup" Date "propagation=" Requires_new "/> </tx:attributes> </tx:advice> <aop:config> <AOP: Pointcut id= "Txpointcut" expression= Execution (* cn.javass. Service.*.* (..)) "
/> <aop:advisor advice-ref= "Txadvice" pointcut-ref= "Txpointcut"/> </aop:config>
Transaction configuration in XML form <tx:method > Attributes detailed
| Property |
Type |
Default value |
Description |
| Propagation |
Propagation enumeration |
REQUIRED |
Transactional propagation Properties |
| Isolation |
Isolation Enumeration |
Defaults (default level of database used) |
Transaction ISOLATION LEVEL |
| ReadOnly |
Boolean |
False |
Do you want to use an optimized read-only transaction |
| Timeout |
Int |
-1 |
Timeout (seconds) |
| Rollbackfor |
Class[] |
{} |
Exception class that needs to be rolled back |
| Rollbackforclassname |
String[] |
{} |
The name of the exception class that needs to be rolled back |
| Norollbackfor |
Class[] |
{} |
Exception classes that do not need to be rolled back |
| Norollbackforclassname |
String[] |
{} |
Exception class name that does not need to be rolled back |
ReadOnly
The readonly flag in the transaction attribute indicates that the corresponding transaction should be optimized for read-only transactions. If the value is true it tells Spring that there is no insert or update in this method, you only need to provide a read-only database connection, which is more efficient than read-write connection, so this is an optimization hint. In some cases, some transaction policies can have a significant optimization effect, such as avoiding dirty checking (attempting to "refresh") when using the Object/relational mapping tool (such as: Hibernate or TopLink).
Timeout
There is also an option in the attribute that defines the "timeout" value, specifying a transaction timeout of several seconds. This property is not normally used. In JTA, this is simply passed to the transaction coordinator for the Java server, and is interpreted accordingly.
5 enumeration values for isolation level (transaction isolation rank)
Why the transaction has to have isolation level this attribute. Review the knowledge of database transactions first:
First class loss update (lost update): In the case of a completely isolated transaction, two things update the same data resource, something terminates abnormally, and the rollback causes the first completed update to be lost at the same time.
The second category of lost updates (second lost updates): is a special case of non repeatable reads, if two transactions are read the same row, then two are written and submitted, the first transaction changes will be lost.
Dirty Read (Dirty Read): If the second transaction queries the update data that was not submitted by the first transaction, a dirty read is formed. Because the first transaction you do not know whether to commit, so the data is not necessarily correct.
Virtual Read (Phantom Read): A transaction executes two queries, the second result set contains no or some rows have been deleted for the first time, resulting in two inconsistent results, except that another transaction inserted or deleted data in the middle of the two queries.
Non-repeatable read (unrepeated Read): One transaction reads the same row of data two times, resulting in different state results, such as the middle of another transaction update the data, two results are not trusted.
Specific about the transaction mechanism can see my previous blog: http://zhou137520.iteye.com/admin/blogs/1638574
When these situations are encountered, we can set the following enumeration values isolation:
Default: Using the database defaults isolation level
SERIALIZABLE: The strictest level, the transaction serial execution, the resource consumes the biggest;
Repeatable_read: Ensures that one transaction does not modify data that has been read by another transaction but not committed (rolled back). "Dirty read" and "non-repeatable reads" are avoided, but more performance damage is caused.
Read_committed: The default transaction level for most mainstream databases ensures that one transaction does not read data that has been modified but not submitted by another parallel transaction, avoiding dirty reads. This level applies to most systems.
Read_uncommitted: Guaranteed that no illegal data was read during the read process. The isolation level is a concurrency problem that handles multiple transactions.
About 7 propagation behaviors of propagation properties
REQUIRED: Specifies that the current method must run in a transactional environment, if the current transaction environment joins the currently executing transaction environment, and if there is no current transaction, a new transaction is created. This is the default value.
SUPPORTS: Specifies that the current method joins the current transaction environment and executes in a non transactional manner if there are currently no transactions.
Mandatory: Specifies that the current method must join the current transaction environment and throw an exception if there is no transaction currently in place.
Requires_new: Specifies that the current method always initiates a new transaction for itself, and if it finds that the current method is already running in a transaction, the original transaction is suspended, and I create a transaction of my own, straight to myself. This method commits the original transaction before it resumes execution.
Not_supported: Specifies that the current method performs an operation in a non transactional manner, and suspends the current transaction if there is a current transaction, and then continues the original transaction as I run out of the transaction state.
NEVER: Specifies that the current method must never be executed within the scope of a transaction, and that if the method executes within a transaction scope, the container throws an exception and executes only if it is not associated with the transaction.
NESTED: Specifies that when the current method executes, if a transaction already exists, it is run in this nested transaction. If the current environment does not run a transaction, creates a new transaction and is independent of the parent transaction, which has multiple guaranteed points to roll back. It means my own. Internal transaction rollback does not affect external transactions and only works with the Datasourcetransactionmanager transaction manager.
Annotation form @transactional Implement transaction management
Note that @transactional can only be applied to the public method, and for other non-public methods, a @transactional is not an error if it is marked, but the method has no transactional functionality.
By default, a method with a transaction rolls back when it encounters runtiomeexception. The exception that is checked is not rolled back, and if you want all the exceptions to be rolled back, add the attribute Rollbackfor={exception.class}
<!--transaction Manager configuration-->
<bean id= "Txmanager" class= " Org.springframework.orm.hibernate3.HibernateTransactionManager ">
<property name=" sessionfactory "ref=" Sessionfactory "/>
</bean>
<!--use annotation to define transaction-->
<tx:annotation-driven Transaction-manager= "Txmanager" proxy-target-class= "true"/>
Transaction-manager: Specifies the name of the transaction manager, which defaults to TransactionManager, and needs to be explicitly specified when using a different name;