Two types of transactions commonly used in spring, as well as the propagation of transactions, isolation levels

Source: Internet
Author: User
Tags aop exception handling naming convention rollback xmlns

In the previous article summed up the spring transaction configuration in 5, but many ways are not and all the parameters used in the configuration is the default parameters, this article on the two commonly used transaction configuration and information configuration transaction propagation, isolation level, and timeouts, and so on.

I. Annotation-type transactions

1, the annotated transaction in peacetime development use quite a lot, the work of the two companies see many projects used this way, below to see the specific configuration demo.

2. Instance of transaction configuration

(1), Spring+mybatis transaction configuration

        <!--define transaction manager--
	<bean id= "TransactionManager"
		class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager ">
		<property name=" DataSource "ref=" DataSource "/>
	</bean>
	<!--using annotation transactions---
	<tx:annotation-driven  transaction-manager= "TransactionManager"/>
	

(2), spring+hibernate transaction configuration

	<!--transaction manager configuration, single data source transaction--
	<bean id= "TransactionManager" class= " Org.springframework.orm.hibernate3.HibernateTransactionManager ">
		<property name=" sessionfactory "ref=" Sessionfactory "/>
	</bean>
	
	<!--using annotation to define transactions--
	<tx:annotation-driven  Transaction-manager= "TransactionManager"   proxy-target-class= "true"/>

See the above two sections of the configuration is not very familiar with this is the configuration of the transaction that we usually see, in the spring configuration to configure the data source is DataSource, transaction manager, the transaction manager using different ORM Framework transaction manager class is different, For example, it uses mybatis, so it's

Org.springframework.jdbc.datasource.DataSourceTransactionManager

If you use Hibernate, the transaction manager class is

Org.springframework.orm.hibernate3.HibernateTransactionManager

This is to be configured when using annotations, the specific annotations in the code, and the propagation of the transaction, the isolation level is generally configured below in the service layer to see

3. @Transactional

(1), here to illustrate, some put this annotation on the class name above, so that you configure the @transactional for all public methods in this class to work

(2), @Transactional method name, only for this method has effect, also must be public method

For example, this method defines a transaction and sets a number of properties at the same time:

	@Transactional (propagation=propagation.required,rollbackfor=exception.class,timeout=1,isolation= Isolation.default) public
	void Saveuser (map<string, string> Map) throws Exception {
         System.out.println ( "Method Start");
		for (int i = 0; i < 500000; i++) {
	            System.out.println ("*");
	        }
		 System.out.println ("Enter and save");
		 Userdao.saveuser (map);
		 System.out.println ("Exit Save");
	}


4. What properties can be configured in a thing configuration

(1), the dissemination of business: @Transactional (propagation=propagation.required)

If there is a transaction, then join the transaction and create a new one (by default)

(2), Transaction timeout: @Transactional (timeout=30)//default is 30 seconds

Note that this is about the timeout of the transaction rather than the timeout of the connection, which is different

(3), the isolation level of the transaction: @Transactional (isolation = isolation.read_uncommitted)

READ UNCOMMITTED data (dirty read, non-repeatable read) basic not used

(4), rollback:

Specify a single exception class: @Transactional (Rollbackfor=runtimeexception.class)

Specify multiple exception classes: @Transactional (Rollbackfor={runtimeexception.class, Exception.class}) This property is used to set an array of exception classes that need to be rolled back. The transaction is rolled back when the exception in the specified exception array is thrown in the method.

(5), Read only: @Transactional (readonly=true)

This property is used to set whether the current transaction is a read-only transaction, set to True for read-only, false to read-write, and the default value to False.

Ok this annotation way to implement the configuration of the transaction and the definition of some properties, in fact, there are a lot of things to pay attention to the matter, if you want to learn more things to learn more, here is just a simple record

So what are we going to pay attention to:

1. Introducing the <tx:> namespace into the spring configuration file: xmlns:tx= "Http://www.springframework.org/schema/tx"

Http://www.springframework.org/schema/tx
Http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

<beans xmlns= "Http://www.springframework.org/schema/beans"
	xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "
	 xmlns:tx=" http://www.springframework.org/schema/tx "
	xmlns:context="/http/ Www.springframework.org/schema/context "
	xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "
	xsi: schemalocation= "Http://www.springframework.org/schema/beans 
	              http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd
				  http://www.springframework.org/schema/context
				  http://www.springframework.org/ Schema/context/spring-context-3.2.xsd
				  HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/ 
                  http Www.springframework.org/schema/aop/spring-aop.xsd		
				 http://www.springframework.org/schema/tx/ 
				 http Www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

2, @Transactional can only be applied to the public method, for other non-public methods, if the tag @transactional will not error, but the method does not have transactional capabilities.

3. With spring transaction manager, Spring is responsible for database open, Commit, rollback. Default run-time exceptions are encountered (the throw new RuntimeException ("comment");) rolled back, that is, the rollback occurs when an exception is encountered that is not checked (unchecked) , while encountering the exception that needs to be caught (the throw new Exception ("comment");) does not roll back, that is, when a check exception is encountered (that is, an exception that is thrown when it is not run-time, the compiler checks for an exception that is called a check exception or a check exception), we specify the way to let the transaction roll To get all the exceptions rolled back, add @Transactional (Rollbackfor={exception.class, other exceptions}). If unchecked exception is not rolled back: @Transactional ( Notrollbackfor=runtimeexception.class)
As follows:
@Transactional (Rollbackfor=exception.class)//Specify Rollback, rollback when an exception Exception is encountered
public void MethodName () {
throw new Exception ("note");

}
@Transactional (Norollbackfor=exception.class)//Specifies no rollback and encounters a run-time exception (the throw new RuntimeException ("note");) is rolled back
Public Itimdaoimpl Getitemdaoimpl () {
throw new RuntimeException ("note");
}

4. @Transactional annotations should only be applied to the public visibility method. If you use @Transactional annotations on protected, private, or package-visible methods, it will not error, but this annotated method will not show the configured transaction settings.


5. @Transactional annotations can be applied to interface definitions and interface methods, class definitions, and public methods of classes. Note, however, that only @Transactional annotations appear to be less than the open transaction behavior, which is only a meta-data that can be used to identify @Transactional annotations and the beans that are configured appropriately to have transactional behavior. In the above example, it is actually the presence of the <tx:annotation-driven/> element that opens the transaction behavior.


6. The spring team's recommendation is that you use @Transactional annotations on specific classes (or methods of classes) rather than on any interface that the class implements. You can certainly use @Transactional annotations on the interface, but this will only take effect if you set up an interface-based proxy. Because annotations are not inherited, this means that if you are using a class-based proxy, the transaction's settings will not be recognized by the class-based proxy, and the object will not be wrapped by the transaction proxy (it will be identified as critical). Therefore, accept the suggestions from the spring team and use @Transactional annotations on specific classes.

second, the use of AOP to implement the configuration of the transaction

1, this kind of transaction use also many, below we take a look at the simple example

2. Example of transaction configuration:

(1), configuration file

<!--definition transaction manager-<bean id= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/> </bean> <!--implemented using AOP facets--<tx:advice id=" Testadvice "transaction-manager=" Tran Sactionmanager "> <!--Configure transactional propagation, isolation levels, and time-out rollback issues--<tx:attributes> <tx:method name=" save* "Propagatio n= "REQUIRED"/> <tx:method name= "del*" propagation= "REQUIRED"/> <tx:method name= "update*" propagation= " REQUIRED "/> <tx:method name=" add* "propagation=" REQUIRED "/> <tx:method name=" * "rollback-for=" Exceptio N "/> </tx:attributes> </tx:advice> <aop:config> <!--configuring transactions Pointcut--<aop:pointcut id=" se Rvices "expression=" Execution (* com.website.service.*.* (..)) "/> <aop:advisor pointcut-ref=" Services "advice-r ef= "Testadvice"/> </aop:config> 
As we can see above, we have simply configured the transaction, where the propagation of the transaction is set in Tx:attributes, the isolation level, and the problem of which the rollback timeout is to be rolled out, that is, you are customizing a transaction to meet your business needs according to your business requirements.

Note: Note here that the configured exception in Rollback_for is configured in Tx:method this is the runtime exception that is rolled back or else the exception is not rolled back.

@Service ("UserService") public
class UserService {
	@Autowired
	private Userdao Userdao;
	public void Saveuser (map<string, string> map) throws Exception {
		 userdao.saveuser (map);
		 throw new RuntimeException ();
		 throw new Exception ();
		 
	}
}

Here we see that if a run-time exception is thrown, it will be rolled back and will not be rolled back if it is not thrown by a run-time exception.

Places to be aware of:

(1), introduced in the spring configuration file: xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"

Http://www.springframework.org/schema/aop
Http://www.springframework.org/schema/aop/spring-aop.xsd

<beans xmlns= "Http://www.springframework.org/schema/beans"
	xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "
	 xmlns:tx=" http://www.springframework.org/schema/tx "
	xmlns:context="/http/ Www.springframework.org/schema/context "
	xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "
	xsi: schemalocation= "Http://www.springframework.org/schema/beans 
	              http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd
				  http://www.springframework.org/schema/context
				  http://www.springframework.org/ Schema/context/spring-context-3.2.xsd
				  HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/ 
                  http Www.springframework.org/schema/aop/spring-aop.xsd		
				 http://www.springframework.org/schema/tx/ 
				 http Www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

(2) Advice (recommended) naming: Because each module will have its own advice, so in the name of the need to make a specification, the initial idea is the module name +advice (just a naming specification).

(3) The Tx:attribute tag is a named type that is configured as a method of a transaction.

such as <tx:method name= "save*" propagation= "REQUIRED"/>

where * is a wildcard, which represents all methods that begin with save, that is, a method that conforms to this naming convention as a transaction.

Propagation= "REQUIRED" represents support for the current transaction, and if no transaction is currently present, create a new transaction. This is the most common choice.

(4) Aop:pointcut tags Configure the classes that participate in the transaction, because the database business operation is performed in the service, and should be the service class that contains the methods that are used as transactions.

The first thing you should pay special attention to is the name of the ID, also because each module has its own transaction facets, so I think the preliminary naming rules because the all+ module name +servicemethod. And the difference between each module also lies in the following sentence:

expression= "Execution (* com.test.testada.test.model.service.*.* (..))"

The first of these * represents the return value, the second * represents the service child package, the third * represents the method name, "(.. ) "represents a method parameter.

(5) The aop:advisor tag is to integrate the transaction management attributes that we have configured above as the whole transaction management.

(6) Pay attention to the marked red place



OK to here two configurations simple demo all have, below we see the Tx:method also have those properties can be configured


Let's take a look at how AOP can be configured in this way to configure those properties:

<tx:advice id= "Advice" transaction-manager= "Txmanager" >
  <tx:attributes>
    <!--properties of Tx:method:
          * Name is required, representing the method name (business method name) associated with the transaction attribute, which refines the pointcut. The wildcard character (*) can be used to specify a batch of methods that are associated to the same transaction property.
                    such as: ' get* ', ' handle* ', ' on*event ' and so on.
          * Propagation  
                            Represents transactional propagation behavior, including required,supports,mandatory,requires_new,not_supported,never,nested
          * Isolation    
                            
          * Timeout      is not a required default value-1 (never timeout)
                            
          
          * Read-only    
                            
          
          * Rollback-for is not a must   
                            Represents the Exception (s) that will be triggered for rollback, separated by commas.
                            
          
          * No-rollback-for is not a must  
                              Represents a Exception (s) that is not triggered for rollback, separated by commas.
                              such as: ' Com.foo. Mybusinessexception,servletexception '
                              
                              
        Any runtimeexception will trigger a rollback of the transaction, but any checked Exception will not trigger a rollback of the transaction                      
     -
     <tx:method name= "save*" propagation= "REQUIRED" isolation= "DEFAULT" read-only= "false"/>
     <tx:method name= "update*" propagation= "REQUIRED" isolation= "DEFAULT" read-only= "false"/>
     <tx:method name= "delete*" propagation= "REQUIRED" isolation= "DEFAULT" read-only= "false"/>
     <!--other methods read-only
     <tx:method name= "*" read-only= "true"/>
  </tx:attributes>
</tx:advice>


OK Two configuration methods we also have a simple study, two configuration methods have what properties to configure we also understand, but, here just said there are two common methods, but not specifically the transaction and transaction configuration brought about by the security of data and performance impact, in fact, the transaction is not so simple, Concrete in-depth study hope to have a summary later.


Here are some of the propagation characteristics of spring transactions:

1. propagation_required: If there is a transaction, the current transaction is supported. If no transaction is turned on
2. Propagation_supports: If there is a transaction, the current transaction is supported. If there is no transaction, the non-transactional execution is
3. Propagation_mandatory: If a transaction already exists, the current transaction is supported. Throws an exception if there is no active transaction.
4. Propagation_requires_new: Always open a new transaction. If a transaction already exists, the existing transaction is suspended.
5. Propagation_not_supported: Always executes in a non-transactional manner and suspends any existing transactions.
6. Propagation_never: Always executes in a non-transactional manner, and throws an exception 7 if there is an active transaction
. Propagation_nested: If an active transaction exists, it is run in a nested transaction. If there is no active transaction, 
      press the Transactiondefinition.propagation_required property to execute
isolation level for spring transactions
1. Isolation_default: This is a platfromtransactionmanager default isolation level, using the default transaction isolation level of the database, and the other four isolation levels corresponding to JDBC
2. Isolation_read_uncommitted: This is the lowest isolation level of a transaction, which allows a foreign transaction to see the uncommitted data of the transaction, which results in dirty reads, non-repeatable reads, and Phantom reads.
3. Isolation_read_committed: Ensures that a transaction modified data is committed before it can be read by another transaction. Another transaction cannot read the uncommitted data of the transaction
4. Isolation_repeatable_read: This transaction isolation level prevents dirty reads and cannot be read repeatedly. However, Phantom reads may occur in addition to ensuring that one transaction cannot read the uncommitted data of another transaction, and that the following conditions are avoided (non-repeatable reads).

The isolation level of the transaction is the same as in the database. You can see the database transaction isolation level, but it's a matter of the nature of the transaction. It looks like you haven't heard it before .

Copy article: http://blog.sina.com.cn/s/blog_4b5bc0110100z7jr.html

We all know the concept of a transaction, so what is the propagation characteristic of the transaction? (Here we focus on the concept of propagation characteristics, the related configuration of the propagation characteristics is not introduced, you can view the official spring documents) when we develop projects with SSH, we usually set the transaction on the service layer So when we call a method of the service layer it can ensure that all of the database updates that we perform in this method remain in one transaction, and that the methods that are called in the transaction layer either all succeed or all fail. Then the communication characteristics of the business are also mentioned here. If you are in this method of your service layer, in addition to calling the methods of the DAO layer, and invoking the other service methods of this class, how does the transaction rule when invoking the other service methods? I have to make sure that the method I'm using in my method is in the same business as my own method, otherwise if things are guaranteed to be consistent. The propagation characteristic of a transaction is to solve this problem, "transactions are propagated" in spring there are multiple configurations for propagation characteristics we use only one of them in most cases: Propgation_ REQUIRED: This configuration item means that when I invoke the service layer method to open a transaction (the method that calls that layer to start creating a transaction, depends on the configuration of your AOP), then when invoking the other methods in this service layer, Creates a new transaction if the current method produces a transaction that is the result of the current method. This work is made by spring to help us do it. We had to manually control the transaction without spring helping us to complete the transaction, for example, when we were using hibernate only in our project, instead of integrating into spring, we called other business logic methods in a service layer, In order to ensure that things must also pass the current Hibernate session to the next method, or by using the Threadlocal method, passing the session to the next method is actually a goal. Now that the work is done by spring, we can focus more on our business logic. Without having to worry about the issues of the business. By default, transactions are rolled back when runtimeexception occurs, so be aware that if you have your own exception handling mechanism to define your own exception in the event of a program error, you must inherit from the RuntimeException class. So the transaction will not be rolled back.

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.