Spring Introduction (c) "Transaction control"

Source: Internet
Author: User

In the development of the need to operate the database, to increase, delete, change the operation of the process belongs to an operation, if in a business need to update more than one table, then any table update failure, the entire business update is a failure, then those who update the successful table must be rolled back, or the business will be wrong, then need to use the transaction, That is, the operation of this business belongs to a transaction, and the transaction is atomic, isolated, consistent and persistent. The transaction is then used, and the purpose of the transaction control is to ensure that a set of operations either succeeds or fails altogether. Spring provides support for transactions, in spring there are two main ways of using transactions, one, programming transaction control, and two, declarative transaction control.

One, programming transaction control

The so-called programmatic transaction control implements the control of a transaction by writing code.

Spring provides a transaction manager to facilitate transactions, and the control of transactions is ultimately controlled through the transaction manager, and all transaction controls in spring must have a transaction manager. Here is an example of a programmatic transaction control, to achieve the transfer between accounts, we put the control of the transaction in the service layer of the system (divided into the controller layer, service layer, DAO layer) to handle, the following is my spring configuration file,

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ SPRING-TX-3.0.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.0.xsd "><!--Spring Automatic detection--><context:component-scan base-package=" Com.cn.study.day5 "/ ><!----><context:property-placeholder location= "classpath:db.properties"/><!----> <bean Id= "DataSource" class= "Org.sPringframework.jdbc.datasource.DriverManagerDataSource "><property name=" Driverclassname "><value> ${db.driver}</value></property><property name= "url" ><value>${db.url}</value></ Property><property name= "username" ><value>${db.username}</value></property>< Property name= "Password" ><value>123456</value></property></bean><bean id= "DAO" class= "Com.cn.study.day5.service.inter.impl.AccountDaoImpl" ><property name= "DataSource" ref= "DataSource" ></property></bean><!--configuration transaction manager--><bean id= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "><property name=" datasource "ref=" DataSource "></property></bean><!--transaction manager templates for ease of use transaction--><bean id=" Transactiontemplate "class=" Org.springframework.transaction.support.TransactionTemplate "><property name=" TransactionManager "ref=" TransactionManager "></propeRty></bean></beans> 

The transaction manager is configured, where Datasourcetransactionmanager is used, and the transaction manager has a DataSource property that must be configured, which uses the ref attribute to refer to the top. With transaction manager to use a transaction or trouble, Spring provides a transaction manager template, we configure the transaction manager template, the transaction manager template requires a transaction manager property, we refer to the transaction manager above. Now that the configuration file for programmatic transaction control is ready, the following is a programmatic development. Because, we put the transaction control on the service layer, below is the code of my service layer,

 PackageCom.cn.study.day5.service.inter.impl;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.stereotype.Component;ImportOrg.springframework.transaction.TransactionStatus;ImportOrg.springframework.transaction.support.TransactionCallback;ImportOrg.springframework.transaction.support.TransactionCallbackWithoutResult;Importorg.springframework.transaction.support.TransactionTemplate;ImportCom.cn.study.day5.service.inter.AccountDaoInter;ImportCom.cn.study.day5.service.inter.AccountServiceIter; @Component Public classAccountserviceimplImplementsAccountserviceiter {@AutowiredPrivateAccountdaointer Adi; @AutowiredPrivatetransactiontemplate tt; //transfer method, from out to in@Override Public voidTransferFinalString out,FinalString in,Final DoubleMoney ) {        //TODO auto-generated Method Stub//using Transaction manager templates for transaction controlTt.execute (NewTransactioncallbackwithoutresult () {@Overrideprotected voidDointransactionwithoutresult (transactionstatus status) {//TODO auto-generated Method StubAdi.outmoney (out, money); //an exception that uses transaction control, and after an exception occurs, the transaction is rolled back                inti = 1/0;            Adi.inmoney (in, money);    }        }); }}

Because it is interface-oriented programming, here I only posted the implementation of the service layer, using the automatic scanning mechanism (scanning class, attribute annotation @component, @Autowired), transfer method is to implement the method of transfer, first transferred from one account, and then transferred to another account , the Execute method using the Transaction manager template requires an instance of Transactioncallback, where anonymous inner classes are used to execute the method in Dointransactionwithoutresult, guaranteeing the control of the transaction.

Transaction control can be ensured in this way, but in the actual development process, the code changes too much and does not conform to the principle of low intrusion development, all of which are seldom used in development, most of which are declarative transaction control.

Ii. Declarative Transaction Control

Declarative transaction control is divided into three ways, one, the declarative transaction control based on Transactionproxyfactorybean agent, the declarative transaction control using AOP, and the declarative transaction control based on @transactional annotations.

1, Transactionproxyfactorybean-based declarative transaction control

Transactionproxyfactorybean is the proxy class for a transaction, and spring generates a proxy for the target class, which is configured as follows.

 <!--configuration transaction Manager-<bean id= "TransactionManager" class  = " Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "></property> </bean> <!--Configure the business layer Agent--<bean id=" Accountserviceproxy "class  = "Org.springframework.transaction.interceptor.TransactionProxyFactoryBean" > <property name= " Target "ref=" Accountserviceimpl "></property> <property name=" TransactionManager "ref=" Transactionmanag Er "></property> <property name=" transactionattributes  "> <props> <prop key=" Transfer "></prop> </props> &L T;/property> </bean> 

Only the configuration of the transaction manager and the business layer agent is posted here, and the remaining data sources and the configuration of the business class can be configured, and the transaction manager is required to configure transaction management regardless of the method used. Focus on the business Layer agent, the configured class attribute is Transactionproxyfactorybean, you need to configure three properties: Target (the specific business layer implementation class to be proxied), TransactionManager (transaction manager), Transactionattributes (The business layer method to intercept). After the configuration is complete, you can test the code as follows,

ApplicationContext ac=getapplicationcontext ();        Accountserviceiter ASI= (accountserviceiter) ac.getbean ("Accountserviceproxy");        Asi.transfer ("AA", "CC", 10d);

The ApplicationContext instance is obtained through the Getapplicationcontext () method, and then an instance of Accountserviceproxy is obtained. This is not an instance of Accountserviceimpl, but an instance object of the proxy, because the proxy is used to proxy the actual business class, and all the actual classes can no longer be used in the proxy class.

The need to configure a proxy for each business class that needs to use the transaction is more cumbersome than teaching, so this approach is rarely used in the development process.

2. Declarative transaction control using AOP

This approach is used in the development process of a more than one, configured as follows,

<!--configuration transaction Manager--    class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >        <property name= "DataSource" ref= "DataSource" ></property>    </bean>    <!--configuration Transaction Enhancements-- >    <tx:advice id= "Advicer" transaction-manager= "TransactionManager" >        <tx:attributes>            <tx:method name= "transfer*" propagation= "REQUIRED"/>        </tx:attributes>    </tx:advice>    <!--configuring pointcuts, transaction Notifications-    <aop:config>        <aop:pointcut id= "mypointcut" expression= "execution (* com.cn.study.day555.service.inter.impl.*.* (..)) " />        <aop:advisor advice-ref= "Advicer" pointcut-ref= "Mypointcut"/>    </aop:config>

The transaction enhancement <tx:advice> configuration is configured to propagate the transaction behavior of the method to be enhanced, such as configuring <aop:config> configuring Pointcuts and corresponding transaction notifications, thus completing the declarative transaction control of AOP.

3, based on @transactional annotations

Using @transactional annotations requires a re-configuration file to enable scanning of this annotation: <tx:annotation-driven transaction-manager= "TransactionManager"/> The transaction manager is referenced, and then you can use the @transactional annotation, which can be used on a class or on a method, using all methods on a class that are on the class, using the method to represent a single method, and to configure some properties. Be explained in a separate article.

Through the description of the above four configuration transactions, in which the second way in the declarative way to use more common, the intrusion of the code is relatively small, the third because the configuration is simple, but also more commonly used, but need to add @transcational annotations on the business class or method, the code has a certain intrusion.

There is an undesirable place to welcome the point, thank you!

Spring Introduction (c) "Transaction control"

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.