How spring Transaction management is implemented: Programmatic transactions and declarative transactions

Source: Internet
Author: User

This article is reproduced in "http://blog.csdn.net/liaohaojian/article/details/70139151" 1. The previous article explained the propagation level and isolation level of spring transactions, as well as the simple configuration of distributed transactions. Click Back to see article 2. Programmatic transactions: Encoding to implement transaction management (code demonstration for JDBC Transaction management) Spring implements programmatic transactions, relying on 2 major categories, respectively, the Platformtransactionmanager mentioned in the previous article, and the template class Transactiontemplat E (recommended). Here is a detailed description of how spring implements transaction management through this class. 1) Platformtransactionmanager, the previous article has explained the details of the method of the class, do not remember to return to see the article.
Transaction Manager Configuration
<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" ><property name= "Jdbcurl" value= "$ {Db.jdbcurl} "/><property name=" user "value=" ${user} "/><property name=" password "value=" ${password} "/ ><property name= "Driverclass" value= "${db.driverclass}"/> <!--the minimum number of connections that are kept in the connection pool. --<property name= "Minpoolsize" > <value>5</value> </property> <!--company The maximum number of connections that are kept in the connection pool.      Default:15--<property name= "Maxpoolsize" > <value>30</value> </property> <!--the number of connections obtained when initializing, the value should be between Minpoolsize and Maxpoolsize. Default:3--<property name= "Initialpoolsize" > <value>10</value> &LT;/PROPERTY&G      T <!--maximum idle time, unused in 60 seconds, the connection is discarded. If 0, it will never be discarded.      default:0--<property name= "MaxIdleTime" > <value>60</value> </property> <!--c3p0 The number of connections that are fetched at the same time when the connection in the connection pool is exhausted. Default:3--<property name= "AcqUireincrement "> <value>5</value> </property> <!--the standard parameters of JDBC to control prepareds loaded within the data source Number of tatements. However, because the pre-cached statements belong to a single connection instead of the entire connection pool.  So setting this parameter takes into account a variety of factors. If both maxstatements and maxstatementsperconnection are 0, the cache is closed.      default:0--<property name= "maxstatements" > <value>0</value> </property> <!--check for idle connections in all connection pools every 60 seconds. default:0--<property name= "Idleconnectiontestperiod" > <value>60</value> </p Roperty> <!--defines the number of repeated attempts to obtain a new connection from the database after a failure. Default:30--<property name= "acquireretryattempts" > <value>30</value> </prop Erty> <!--getting a connection failure will cause any thread that waits for the connection pool to get the connection to throw an exception. However, the data source is still valid and continues to try to get the connection the next time you call Getconnection (). If set to True, the data source will declare broken and permanently shut down after attempting to acquire a connection failure.      Default:false--<property name= "Breakafteracquirefailure" > <value>true</value> </property> <!--because of its high performance, use it only when you need it. If set toTrue then officer the validity of each connection submission. We recommend using methods such as Idleconnectiontestperiod or automatictesttable to improve the performance of your connectivity tests.      Default:false--<property name= "Testconnectiononcheckout" > <value>false</value> </property> </bean><!-- Datasourcetransactionmanager is located under the Org.springframework.jdbc.datasource package, a data source transaction management class that provides transaction management for a single javax.sql.DataSource data source, primarily for jdbc,m Ybatis Framework transaction Management. --><bean id= "TransactionManager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" ><property name= "DataSource" ref= "DataSource"/></bean>
Use code in business (shown in test Class)
Import Java.util.map;import javax.annotation.resource;import javax.sql.datasource;import Org.apache.log4j.Logger; Import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.jdbc.core.jdbctemplate;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import Org.springframework.transaction.platformtransactionmanager;import Org.springframework.transaction.transactiondefinition;import Org.springframework.transaction.TransactionStatus; Import org.springframework.transaction.support.DefaultTransactionDefinition; @RunWith ( Springjunit4classrunner.class) @ContextConfiguration (locations = {"Classpath:spring-public.xml"}) public class Test { @Resourceprivate Platformtransactionmanager Txmanager; @Resourceprivate DataSource datasource;private Static JdbcTemplate JdbcTemplate;    Logger Logger=logger.getlogger (Test.class); private static final String Insert_sql = "INSERT into testtranstation (SD) VALUES (?)"; private static final String count_sql = "Select COUNT (*) from testtranstation"; @Testpublic void Testdelivery () {//define Transaction ISOLATION Level      , propagation behavior, defaulttransactiondefinition def = new Defaulttransactiondefinition ();      Def.setisolationlevel (transactiondefinition.isolation_read_committed);      Def.setpropagationbehavior (transactiondefinition.propagation_required); The transaction state class, obtained from the transaction definition by the Gettransaction method of the Platformtransactionmanager, and when the transaction state is obtained, spring determines how the transaction is opened based on the propagation behavior Transactionstatus      Status = Txmanager.gettransaction (Def);    JdbcTemplate = new JdbcTemplate (DataSource);      int i = Jdbctemplate.queryforint (count_sql);    SYSTEM.OUT.PRINTLN ("Total number of records in the table:" +i);          try {jdbctemplate.update (insert_sql, "1");  Txmanager.commit (status);  Commit a transaction that is bound in status} catch (RuntimeException e) {txmanager.rollback (status);      Rollback} i = Jdbctemplate.queryforint (count_sql); SYSTEM.OUT.PRINTLN ("Total number of records in table:" +i);}}

2) using Transactiontemplate, this class inherits the interface Defaulttransactiondefinition, which is used to simplify transaction management, and transaction management is defined by the template class. is specified primarily through the Transactioncallback callback interface or the Transactioncallbackwithoutresult callback interface. Automatically enjoy transaction management by calling the execute method of the template class with the parameter type Transactioncallback or Transactioncallbackwithoutresult.

Transactiontemplate the callback interface used by the template class:

    • Transactioncallback: Define the operation code that requires transaction management by implementing the "T Dointransaction (Transactionstatus status)" Method of the interface;
    • Transactioncallbackwithoutresult: Inherits the Transactioncallback interface, providing "void Dointransactionwithoutresult (TransactionStatus Status) "Convenience interfaces are used to facilitate transaction operation code that does not require a return value.

Or how to demonstrate it in a test class way

@Testpublic void Testtransactiontemplate () {jdbctemplate = new JdbcTemplate (dataSource);    int i = Jdbctemplate.queryforint (count_sql);      SYSTEM.OUT.PRINTLN ("Total number of records in table:" +i);//constructor initialization transactiontemplatetransactiontemplate template = new Transactiontemplate (Txmanager); Template.setisolationlevel (transactiondefinition.isolation_read_committed);  Overriding the Execute method to implement transaction management Template.execute (new Transactioncallbackwithoutresult () {@Overrideprotected void Dointransactionwithoutresult (transactionstatus status) {jdbctemplate.update (Insert_sql, "starving");   field SD is int type, so insert positive failure report exception, auto Rollback, on behalf of Transactiontemplate Automatic Management Transaction}}); i = Jdbctemplate.queryforint (count_sql);      SYSTEM.OUT.PRINTLN ("Total number of records in table:" +i);}
3. Declarative transactions: It is obvious that every implementation of a programmatic transaction is implemented separately, but when the business volume is complex, the use of programmatic transactions is undoubtedly painful, and declarative transactions are not intrusive and do not affect the implementation of business logic. There are 2 types of declarative transaction implementations, one for the implementation of the AOP-related configuration by using spring's <tx:advice> definition transaction notifications, and one for implementing transaction management through @transactional, with detailed instructions on how to configure the 2 methods, Already relevant note 1) mode one, the configuration file is as follows
<!--<tx:advice> define transaction notifications, which specify transaction properties, where the "Transaction-manager" attribute specifies the transaction manager, and by <tx:attributes> specifies the specific method to intercept <tx:method> interception methods, where parameters are: Name: Method names, inject a matching method into transaction management, wildcard propagation: Transaction propagation behavior, Isolation: Transaction isolation level definition; default Timeout: Transaction time-out setting, in seconds, Default-1, indicating that the transaction time-out will depend on the underlying transaction system; Read-only: Transaction read-only setting, default = False, not read-only, rollback-for: Exception definition to trigger rollback, define multiple to " , "split, default any runtimeexception will cause the transaction to be rolled back, and any checked Exception will not cause the transaction to be rolled back; No-rollback-for: Exception (s) not to be triggered for rollback; can define multiple, with", " --><tx:advice id= "Advice" transaction-manager= "TransactionManager" ><tx:attributes> <!-- The method that intercepts the start of Save, the transaction propagation behavior is: REQUIRED: Must have the transaction, if does not have in the context creates a--><tx:method name= "save*" propagation= "REQUIRED" isolation= "read_committed" timeout= "" read-only= "false" no-rollback-for= "" rollback-for= ""/><!--support, if any, There is no--><tx:method name= "*" propagation= "SUPPORTS"/></tx:attributes></tx:advice><!-- Define the pointcut, expression is the cut-point expressions, as follows, specify all the methods under the Impl package, specifically to customize--><aop:config> <aop:pointcut expression= "EXecution (* com.kaizhi.*.service.impl.*.* (..)) "id=" Pointcut "/> <!--<aop:advisor> define pointcuts, with notifications, Associating TX with AOP configuration is the complete declarative transaction configuration--<aop:advisor advice-ref= "advice" pointcut-ref= "Pointcut"/></aop:config >
For transaction propagation behavior and isolation levels, refer to http://blog.csdn.net/liaohaojian/article/details/68488150 Note:
    1. Transaction rollback exceptions can only be runtimeexception exceptions, and checked exception exceptions are not rolled back, and catch exceptions are not thrown or rolled back. However, the transaction can be forced to roll back: Transactionaspectsupport.currenttransactionstatus (). Isrollbackonly ();
    2. Resolve "self-invocation" caused by the inability to set the correct transaction property issues, refer to http://www.iteye.com/topic/1122740
2) mode two implement transaction management through @transactional
class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >        <property name= " DataSource "ref=" DataSource "/></bean>    // open transaction Annotations
@Transactional (propagation=propagation.required,isolation=isolation.read_committed), specific parameters with the above <tx:method> In the same
Spring provides @transaction annotation transaction management, which also internally uses the surround notification transactioninterceptor to enable and disable transactions.
Note Points using @transactional:
    1. If @transactional annotations are specified on an interface, implementation class, or method, the order of precedence is method > implementation Class > interface;
    2. It is recommended that you use @transactional only on methods that implement a class or implementation class, not on an interface, because if you use the JDK proxy mechanism ( an interface-based proxy ) is not a problem, and you encounter problems using the Cglib Proxy (inheritance) mechanism. Because it uses a class-based proxy instead of an interface, this is because the @transactional annotation on the interface is "not inheritable ";









How spring Transaction management is implemented: Programmatic transactions and declarative transactions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.