Four ways of spring transaction management (take bank transfers as an example)

Source: Internet
Author: User
Tags aop rollback

This article supporting sample code download address (complete can run, including SQL files, download, please modify the database configuration): http://download.csdn.net/detail/daijin888888/9567096
I. The role of affairsControl a number of database operations as an overall success or failure together.
of Atomic: Refers to the transaction is an indivisible work unit, the operation in the transaction either occurs, or does not occur.
Consistency: Refers to the integrity of the data before and after the transaction must remain consistent.
Isolation of: When multiple users access a database concurrently, a user's transaction cannot be interfered by another user's transactions, and data between multiple concurrent transactions is isolated from one another.
Persistence of: When a transaction is committed, its changes to the data in the database are permanent, and the instant database failure should not have any effect on it.
two, spring transaction management high-level abstraction mainly includes 3 interfaces--Platform TransactionManagerTransaction manager (Commit, ROLLBACK TRANSACTION)
Spring provides different platform TransactionManager interface implementations for different persistence frameworks. Such as:
Use the Datasourcetransactionmanager when persisting data using spring JDBC or ibatis
Use Hibernatetransactionmanager when persisting data using the Hibernate3.0 version
--transactiondefinitionTransaction definition information (quarantine, propagation, timeout, read-only)
Dirty reads: A transaction reads data that is overwritten by another transaction but has not yet been committed, and if the data is rolled back, the data read is invalid.
Non-repeatable reads: The results returned by reading the same data multiple times in the same transaction are different.
Phantom reads: When a transaction reads several rows of records, another transaction inserts some records, and the Phantom reads. Later in the query, the first transaction will find some records that were not originally.
Transaction ISOLATION Level: (Five kinds)
default--uses the default isolation level of the back-end database (the selection in spring) read_uncommited--allows you to read the changed data that has not yet been submitted. may result in dirty, Phantom, and non-repeatable reads read_committed--allow read after concurrent transactions have been committed. Prevents dirty reads, but Phantom and non repeatable reads can still occur repeatable_read--is consistent with multiple reads of the same field, unless the data is changed by the transaction itself. Prevents dirty, repeatable reads, but Phantom reads can still occur serializable--completely compliant with acid isolation levels to ensure that dirty, phantom, and non repeatable reads do not occur. This is the slowest of all isolation levels, and it is typically done by completely locking the data tables involved in the transaction
where MySQL defaults to the Repeatable_read isolation level; Oracle defaults to read_committed isolation level

Transaction propagation behavior: (Seven kinds)
required--supports the current transaction and creates a new transaction if there are currently no transactions.     This is the most common choice.     supports--supports the current transaction and executes it in a non transactional manner if there are currently no transactions.     mandatory--supports the current transaction and throws an exception if there are currently no transactions.     requires_new--creates a new transaction and suspends the current transaction if there is currently a transaction.     not_supported--performs an operation in a non transactional manner and suspends the current transaction if there is a current transaction.     never--executes in a non transactional manner and throws an exception if there is a current transaction. nested--executes within a nested transaction if a transaction is currently present. If there is currently no transaction, a similar operation is performed with required. Has more than one savepoint that can be rolled back, and internal rollback does not affect external transactions. Valid only for Datasourcetransactionmanager
--TransactionstatusTransaction specific running state
Spring provides the following methods for controlling transactions
A. Programmatic transaction management (based on Java programming control, rarely used)--see DEMO1 package
Encapsulate multiple DAO operations with Transactiontemplate
*b. Declarative transaction management (AOP configuration control based on spring)
-based on the Transactionproxyfactorybean approach. (rarely used)--See Demo2 package
You need to configure a Transactionproxyfactorybean for each class that has transaction management.
-based on XML configuration (frequently used)--See Demo3 bag
Once configured, there is no need to add anything on the class.
If the action plunges into a transaction as the target object, you need to add the proxy-target-class= "true" attribute to the <aop:config> element. The reason is to inform the spring framework of using cglib technology to generate an action class with transaction management capabilities.
-based on annotations (simple configuration, often used)--See Demo4 bag
Open the transaction annotation configuration in Applicationcontext.xml. (Applicationcontext.xml only need to define the bean and append the following elements)
<bean id= "Txmanager" class= "...". >
<property name= "Sessionfactory" >
</property>
<tx:annotation-driven transaction-manager= "Txmanager"/>

Use @transactional in the target component class, which can be defined before the class or before the method. Iv. Examples (Bank transfers)

--Programming type

/**
 * @Description: The DAO layer interface of the transfer case */public
interface Accountdao {
	/**
	 * @param out
	 *            : Transfer Account
	 * @param            Money *: Transfer amount/public
	void Outmoney (String out, Double);

	/**
	 * * 
	 @param in
	 *: Transfer to            account
	 * @param            Money *: Transfer amount/public
	void Inmoney (String in, Double);
}

/**
 * @Description: The DAO Layer implementation class of the transfer case *
 * * Public
class Accountdaoimpl extends Jdbcdaosupport implements Accountdao {
	/**
	 * @param
	 out *            : Transfer account
	 * @param            Money *: Transfer amount/
	@Override Public
	void Outmoney (string out, Double) {
		String sql = ' Update account set ' = money-? WHERE name =? ";
		This.getjdbctemplate (). Update (SQL, money, out);
	}
	/**
	 * @param in
	 *            : Transfer to account
	 * @param            Money *: Transfer
	 Amount
	* * * @Override public void Inmoney (string in, Double) {
		String sql = ' Update account set ' = money+? WHERE name =? ";
		This.getjdbctemplate (). Update (SQL, Money, in);
	}
}

/**
 * @Description: Business interface for transfer cases
 */public
interface Accountservice {
	/**
	 * @param out	: Turn out account
	 * @param	in: Transfer account
	 * @param	Money: Transfer amount
	 /public
	void Transfer (String out, String in,double money);

/** * @Description: The business Layer implementation class of the transfer case/public class Accountserviceimpl implements Accountservice {//inject transfer DAO private Acco

	Untdao Accountdao;

	Inject the template of the transaction management private Transactiontemplate transactiontemplate; /** * @param out *: Transfer account * @param in *: Transfer account * @param money *: Transfer amount * * @Ov Erride public void Transfer (final string out, final string in, Final Double) {//Business processing without transaction control, if an exception occurs in the process, leading to the previous
		Can be completed, the latter can not, that is, transfer successful but did not receive the transfer//Accountdao.outmoney (out, money);
		int i = 1/0;

		Accountdao.inmoney (in, money); Transactiontemplate.execute (New Transactioncallbackwithoutresult () {@Override protected void Dointransactionwithou
				TResult (Transactionstatus transactionstatus) {Accountdao.outmoney (out, money);
			int i = 1/0;//transaction control, that is, an exception occurs in which the code executes the invalid Accountdao.inmoney (in, money);
	}
		});
	public void Setaccountdao (Accountdao accountdao) {This.accountdao = Accountdao; } public void SettransactiontemplatE (transactiontemplate transactiontemplate) {this.transactiontemplate = transactiontemplate; }
}

Applicationcontext1.xml

<!--introduce an external property file--> <context:property-placeholder location= "classpath:jdbc.properties"/> <!-- Configure the C3P0 connection pool--> <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <property name= " Driverclass "value=" ${jdbc.driverclass} "/> <property name=" Jdbcurl "value=" ${jdbc.url} "/> <property name = "User" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.password}"/> </bean> ;! --Configure Business layer class--> <bean id= "Accountservice" class= "Com.zs.spring.demo1.AccountServiceImpl" > <property name= " Accountdao "ref=" Accountdao "/> <!--injection template for transaction management--> <property name=" transactiontemplate "ref=" transactionTe Mplate "/> </bean> <!--Configure the DAO class (simplified, automatically configure JdbcTemplate)--> <bean id=" Accountdao "class=" com.zs.spring . Demo1.
	Accountdaoimpl "> <property name=" dataSource "ref=" DataSource "/> </bean> <!--configuring DAO classes (not simplified)--> <!--<bean id= "JdbctemplatE "class=" Org.springframework.jdbc.core.JdbcTemplate "> <property name=" dataSource "ref=" DataSource "/> < /bean> <bean id= "Accountdao" class= "Com.zs.spring.demo1.AccountDaoImpl" > <property name= "JdbcTemplate" ref= "JdbcTemplate"/> </bean>--> <!--==================================1. Programmatic Transaction Management ================= ==============================--> <!--configuration transaction manager--> <bean id= "TransactionManager" Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/> </bean> <!--Configure transaction Management templates: Spring provides classes--> <bean id=" transactiontemplate "CLA to simplify transaction management code ss= "Org.springframework.transaction.support.TransactionTemplate" > <property name= "TransactionManager" TransactionManager "/> </bean>

Test:

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration ("Classpath:applicationContext1.xml")
public class Transactiontest {
	@Resource (name = "Accountservice")
	private accountservice accountservice;

	@Test public
	void Demo1 () {
		accountservice.transfer ("AAA", "BBB", 200d);
	}

--based on the Transactionproxyfactorybean approach

public class Accountserviceimpl implements Accountservice {
	//inject money into the DAO
	private Accountdao Accountdao;

	/**
	 * @param
	 out *            : Transfer account
	 * @param in
	 *: Transfer account *
	 @param            Money *: Transfer amount
	 * *
	@Override public
	void Transfer (string out, string in, Double) {
		Accountdao.outmoney; c16/>//int i = 1/0;
		Accountdao.inmoney (in, Money);
	}

	public void Setaccountdao (Accountdao accountdao) {
		This.accountdao = Accountdao;
	}
}

Applicationcontext2.xml

<!--introduce an external property file--> <context:property-placeholder location= "classpath:jdbc.properties"/> <!-- Configure the C3P0 connection pool--> <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <property name= " Driverclass "value=" ${jdbc.driverclass} "/> <property name=" Jdbcurl "value=" ${jdbc.url} "/> <property name = "User" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.password}"/> </bean> ;! --Configure Business layer class--> <bean id= "Accountservice" class= "Com.zs.spring.demo2.AccountServiceImpl" > <property name= "  Accountdao "ref=" Accountdao/> </bean> <!--Configure the DAO class (simplified, automatically configure JdbcTemplate)--> <bean id= "Accountdao"
	
	class= "Com.zs.spring.demo2.AccountDaoImpl" > <property name= "dataSource" ref= "DataSource"/> </bean> <!--==================================2. Transactional management with XML configuration declarative (original) ============================================== =--> <!--configuration transaction manager--> <bean id= "tRansactionmanager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name = "DataSource" ref= "DataSource"/> </bean> <!--Configure the agent for the business layer--> <bean id= "Accountserviceproxy" O Rg.springframework.transaction.interceptor.TransactionProxyFactoryBean > <!--Configure the target object--> <property name = "Target" ref= "Accountservice"/> <!--inject transaction manager--> <property name= "TransactionManager" ref= "Transactionman" Ager "></property> <!--inject the properties of the transaction--> <property name=" Transactionattributes "> <props> & lt;! --Prop format: * Propagation: Transaction propagation behavior * Isotation: Transaction ISOLATION LEVEL * ReadOnly: Read Only *-exception: what happens Frequently ROLLBACK TRANSACTION * +exception: Which exceptions occur do not ROLLBACK TRANSACTION--> <prop key= "Transfer" >PROPAGATION_REQUIRED</prop> &L t;! --<prop key= "Transfer" >PROPAGATION_REQUIRED,readOnly</prop>--> <!--<prop key= "Transfer" > Propagation_required,+java.lang.arithmeticexception</prop>--> </props> </property> </bean> 

Test:

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration ("Classpath:applicationContext2.xml")
public class Transactiontest {
	/**
	 * Must inject the proxy class: Because the proxy class does an enhanced
	 operation
	///@Resource (name= "Accountservice")
	@Resource (name = "Accountserviceproxy")
	private accountservice accountservice;

	@Test public
	void Demo1 () {
		accountservice.transfer ("AAA", "BBB", 200d);
	}

--Based on XML configuration

public class Accountserviceimpl implements Accountservice {
	//inject money into the DAO
	private Accountdao Accountdao;

	/**
	 * @param
	 out *            : Transfer account
	 * @param in
	 *: Transfer account *
	 @param            Money *: Transfer amount
	 * *
	@Override public
	void Transfer (string out, string in, Double) {
		Accountdao.outmoney; c16/>//int i = 1/0;
		Accountdao.inmoney (in, Money);

	}

	public void Setaccountdao (Accountdao accountdao) {
		This.accountdao = Accountdao;
	}
}

Applicationcontext3.xml

<!--introduce an external property file--> <context:property-placeholder location= "classpath:jdbc.properties"/> <!-- Configure the C3P0 connection pool--> <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <property name= " Driverclass "value=" ${jdbc.driverclass} "/> <property name=" Jdbcurl "value=" ${jdbc.url} "/> <property name = "User" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.password}"/> </bean> ;! --Configure Business layer class--> <bean id= "Accountservice" class= "Com.zs.spring.demo3.AccountServiceImpl" > <property name= "  Accountdao "ref=" Accountdao/> </bean> <!--Configure the DAO class (simplified, automatically configure JdbcTemplate)--> <bean id= "Accountdao"
	
	class= "Com.zs.spring.demo3.AccountDaoImpl" > <property name= "dataSource" ref= "DataSource"/> </bean> <!--==================================3. Transactional management Using XML configuration declarative, based on tx/aop=========================================== = = =--> <!--configuration transaction manager--> <bean ID= "TransactionManager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property Name= "DataSource" ref= "DataSource"/> </bean> <!--Configure transaction notifications--> <tx:advice id= "Txadvice" transaction -manager= "TransactionManager" > <tx:attributes> <!--propagation: Transactional propagation behavior Isolation: Isolation levels for transactions R Ead-only: Read-only rollback-for: Which exceptions occur no-rollback-for: Which exceptions do not roll back timeout: expired information--> <tx:method "Transfer" propagation= "REQUIRED"/> </tx:attributes> </tx:advice> <!--configuration Slice--> <aop:config > <!--configuration pointcut--> <aop:pointcut expression= "Execution (* com.zs.spring.demo3.accountservice+.* (..))" Id= "PO Intcut1 "/> <!--configuration slice--> <aop:advisor advice-ref=" Txadvice "pointcut-ref=" pointcut1 "/> </aop:config >

Test:

/**
 * @Description: Spring's declarative transaction management approach two: ASPECTJ-based XML configuration
/@RunWith (Springjunit4classrunner.class)
@ContextConfiguration ("Classpath:applicationContext3.xml") public
class Transactiontest {
	/**
	 * Must inject proxy class: Because the proxy class carries on the enhancement operation
	 * * *
	@Resource (name = "Accountservice")
	private accountservice accountservice;

	@Test public
	void Demo1 () {
		accountservice.transfer ("AAA", "BBB", 200d);
	}

--Based on annotations

 Properties in/** * @Transactional propagation: Propagation behavior of a transaction isolation: Isolation level of transaction readOnly: Read Only
 *                     rollbackfor: What exception rollback occurs Norollbackfor: What happens when the exception is not rolled back
 *                     rollbackforclassname the Exception class name rollback
/@Transactional (propagation = propagation.required, isolation = Isolation.default, readOnly = false) public
class Accountserviceimpl implements Accountservice {
	//inject transfer of DAO
	private Accountdao Accountdao;

	/**
	 * @param
	 out *            : Transfer account
	 * @param in
	 *: Transfer account *
	 @param            Money *: Transfer amount
	 */
	@Override public
	void Transfer (string out, string in, Double) {
		Accountdao.outmoney, Money);
		int i = 1/0;
		Accountdao.inmoney (in, Money);
	}

	public void Setaccountdao (Accountdao accountdao) {
		This.accountdao = Accountdao;
	}
}

Applicationcontext4.xml

<!--introduce an external property file--> <context:property-placeholder location= "classpath:jdbc.properties"/> <!-- Configure the C3P0 connection pool--> <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <property name= " Driverclass "value=" ${jdbc.driverclass} "/> <property name=" Jdbcurl "value=" ${jdbc.url} "/> <property name = "User" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.password}"/> </bean> ;! --Configure Business layer class--> <bean id= "Accountservice" class= "Com.zs.spring.demo4.AccountServiceImpl" > <property name= "  Accountdao "ref=" Accountdao/> </bean> <!--Configure the DAO class (simplified, automatically configure JdbcTemplate)--> <bean id= "Accountdao"
	
	class= "Com.zs.spring.demo4.AccountDaoImpl" > <property name= "dataSource" ref= "DataSource"/> </bean> <!--==================================4. Use annotations to configure declarative transactions ============================================--> <!- -Configure the transaction manager--> <bean id= "TransactionmanaGer "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource " ref= "DataSource"/> </bean> <!--open annotation transaction--> <tx:annotation-driven transaction-manager= "transactionm
	 Anager "/>

Test:

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration ("Classpath:applicationContext4.xml")
public class Transactiontest {

	/**
	 * Must inject the proxy class: Because the proxy class does an enhanced
	 operation
	/@Resource (name = "Accountservice")
	private Accountservice Accountservice;

	@Test public
	void Demo1 () {
		accountservice.transfer ("AAA", "BBB", 200d);
	}

Specific code and database file reference project complete code:

http://download.csdn.net/detail/daijin888888/9567096

Reprint please indicate the source:

http://blog.csdn.net/daijin888888/article/details/51822257


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.