Spring Transaction management (declarative transactions and programmatic transactions)

Source: Internet
Author: User
Tags aop connection pooling stub

Spring's transaction management is divided into: declarative transactions and programmatic transactions

Spring on transaction management is usually divided into three parts: DataSource, TransactionManager and agent mechanism of the three parts, regardless of which configuration, the general change is only the agent mechanism this part.

1.spring Data Source Configuration
* Method 1: Configure the data source directly in spring's configuration file (Applicationcontext.xml)

<span style= "White-space:pre" > </span><!--Configuration Data Source (DBCP database connection pooling mode)--<bean id= "DataSource" class= " Org.apache.commons.dbcp.BasicDataSource "> <!--Configuration database driver-<property name=" Driverclassname "value=" Com.mysql.jdbc.Driver "/> <!--configuration URL--<property name=" url "value=" Jdbc:mysql://localhost:3306/spring_ Transaction "/> <!--Configure user name and password--<property name=" username "value=" root "/> <property name=" password 
		"Value=" root "/> <!--initial value of connection pool startup--<property name=" InitialSize "value=" Up "/> <!--the maximum connection pool value--  <property name= "Maxactive" value= "$"/> <!--maximum idle value, when a peak time passes, the connection pool can slowly release a portion of the unused connection slowly--<property Name= "Maxidle" value= "2"/> <!--minimum idle value, when the number of idle connections is less than the threshold, the connection pool will pre-request some connections to avoid flooding when the peak comes---<property name= "Minidle" Val ue= "1"/> </bean> <!--configuration Sessionfactory-<bean id= "sessionfactory" class= "Org.springframework.orm . Hibernate3. Localsessionfactorybean "&GT <!--Configure the data source associated with it-<property name= "DataSource" ref= "DataSource"/> <!--Configuration Mapping resource--<property NA Me= "Mappingresources" > <list> <value>com/zm/model/User.hbm.xml</value> </list> < /property> <!--configuring Hibernate other related properties-<property name= "hibernateproperties" > <value> Hib Ernate.dialect=org.hibernate.dialect.mysqldialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update </va Lue> </property> </bean>
* Way 2: In spring configuration file, hibernate configuration file is loaded Hibernate.cfg.xml
<span style= "White-space:pre" >	</span>< configuration of!--data sources and sessionfactory--
	<bean id= " Sessionfactory "class=" Org.springframework.orm.hibernate3.LocalSessionFactoryBean ">
		<property name=" Configlocation "value=" Classpath:hibernate.cfg.xml "/>
There are several ways to configure a data source (DataSource), where the DBCP connection pool is used, and two packets Commons-dbcp.jar and Commons-pool.jar are introduced.

Note: If you use the second method, you can configure the data source in hibernate and then introduce the Hibernate profile, but the data source says that Hibernate3 already does not support DBCP connection pool configuration DataSource because Dbcp has a bug (not sure what bugs).

2.spring Transaction Management

The first part of the primary configuration data source (DataSource), and then the configuration of TransactionManager, because spring does not have to configure TransactionManager regardless of which transaction management is used, so This is part of the public configuration section of the transaction management configuration.

<span style= "White-space:pre" >	</span>* First Configure the transaction manager, either way you need to configure the transaction manager
	<!--configuration transaction manager (declarative transactions)- -
	<bean id= "TransactionManager" class= "Org.springframework.orm.hibernate3.HibernateTransactionManager ">
		<property name=" sessionfactory "ref=" sessionfactory "></property>
The last configuration is proxy mode.

There are 3 ways to configure declarative transactions (there are 4 of them):

Mode 1: Use the TX label method

<span style= "White-space:pre" >	</span><tx:advice id= "Txadvice" transaction-manager= " TransactionManager ">
			<tx:method name=" add* "propagation=" REQUIRED "/>
			<tx:method name= "del*" propagation= "REQUIRED"/>
			<tx:method name= "modify*" propagation= "REQUIRED"/>
			<tx:method name= "*" read-only= "true"/>
	<AOP: config>
		<aop:pointcut id= "Userdaomethod" expression= "Execution (* com.zm.dao.userdao*.* (..))" />
		<aop:advisor pointcut-ref= "Userdaomethod" advice-ref= "Txadvice"/>
This is a typical AOP implementation,<tx:advice> is a specific implementation of a transaction (equivalent to a management rule for transaction Management),<aop:config> Configure the facets (or specific classes) to participate in the transaction

For example: <tx:method name= "add*" propagation= "REQUIRED"/> means that the method that begins with "add", the transaction propagation feature is "REQUIRED", propagation represents the propagation characteristics of the transaction, You can also configure additional properties.

Method 2: How to use the proxy

First, declare a transactionproxy, which is equivalent to a rule that defines a transaction

Then, for each bean that implements this transaction rule, the transaction proxy bean is inherited, and a proxy DAO is generated.

<span style= "White-space:pre" >	</span><!--Configure a transaction proxy bean, which is equivalent to a parent class, and other specific beans can inherit the bean. You can then generate a proxy bean--
<span style= "White-space:pre" >	</span><bean id= "Transactionproxy" class= " Org.springframework.transaction.interceptor.TransactionProxyFactoryBean "abstract=" true ">
	 	<property Name= "TransactionManager" ref= "TransactionManager"/>
	 	<property name= "Transactionattributes" >
	 			<prop key= "add*" >PROPAGATION_REQUIRED</prop>
	 			<prop key= "del*" > propagation_required</prop>
	 			<prop key= "modify*" >PROPAGATION_REQUIRED</prop>
	 			<prop key= "*" >PROPAGATION_REQUIRED,readOnly</prop>
	 </bean >
	 <bean id= "Userdaoproxy" parent= "Transactionproxy" >
	 	<property name= "target" ref= "Userdao"/ >
It should be explained that this configuration is equivalent to the transaction Agent Bean is a public transaction management configuration, but now if there are two DAO used by different management methods, then you need to configure the transaction management in each agent DAO, therefore, This type of proxy can be divided into two configurations: 1. All beans are common to one transaction agent bean;2. Each bean is configured with a separate transaction agent

Mode 3: Interceptor mode

First define a transaction interceptor and then configure which classes the interceptor will use for

<span style= "White-space:pre" > </span><bean id= "transactioninterceptor" class= " Org.springframework.transaction.interceptor.TransactionInterceptor "> <property name=" TransactionManager " ref= "TransactionManager"/> <property name= "transactionattributes" > <props> <prop key= "add*" & Gt propagation_required</prop> <prop key= "del*" >PROPAGATION_REQUIRED</prop> <prop key= "modify* ">PROPAGATION_REQUIRED</prop> <prop key=" * ">PROPAGATION_REQUIRED,readOnly</prop> </props&
	 	Gt </property> </bean> <bean class= " Org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator "> <property name=" beannames "> < list> <value>*Dao</value> </list> </property> <property name= "Interceptorname
	 S "> <list> <value>transactionInterceptor</value> </list> </property></bean> 

The above is how declarative transactions are configured,

Programmatic Transaction Configuration method

Method 1: Full annotation

Programmatic transactions only need to turn on annotations in the configuration file, and others can be configured using annotations in specific DAO.

	<!--opening annotations--
<span style= "White-space:pre" >	</span><tx:annotation-driven transaction-manager= " TransactionManager "/>

	The specific program code
	@Transactional public
	class Userdaoimpl implements Userdao {
		private sessionfactory sessionfactory;
		public void Setsessionfactory (Sessionfactory sessionfactory) {
			this.sessionfactory = sessionfactory;
			System.out.println ("sessionfactory:" + sessionfactory);
		@Transactional (propagation=propagation.required,rollbackforclassname= "Exception") public
		Void AddUser (user user) {
			//TODO auto-generated Method stub
			session = NULL;
			Session = Sessionfactory.getcurrentsession ();
			Session.save (user);
		@Transactional (readonly=true) public
		list<user> showusers () {
			//TODO auto-generated Method stub
			return null;
Note: Some blogs write to the phrase "<context:annotation-config/>" in the config file, but I do not deserve it, and I do not know why, maybe it is related to the spring version. (guessed, not measured)

3. Precautions

* If a declarative transaction is configured, the transaction is rolled back when a run-time exception occurs, but the transaction does not roll back when a non-runtime exception occurs.

* If a programmatic transaction is configured, the transaction will be rolled back regardless of the exception.

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.