Spring transaction management-Configuring transactions with annotations

Source: Internet
Author: User

I. Overview

Transaction management is critical for enterprise applications, and it guarantees data consistency even in the event of an exception. The Spring framework provides a consistent abstraction of transaction management with the following characteristics: providing a consistent programming model for different transactional APIs, such as JTA (Java Transaction API), JDBC, Hibernate, JPA (Java Persistence API and JDO (Java Data Objects) Support declarative transaction management, especially annotation-based declarative transaction management, simple and easy-to-use
Provides a much simpler programmatic transaction management API than other transactional APIs such as JTA and the perfect integration of spring data access Abstraction .

1.1. How to manage the affairs

Spring supports both programmatic transaction management and declarative transaction management. Programmatic transaction management uses Transactiontemplate or uses the underlying platformtransactionmanager directly. For programmatic transaction management, Spring recommends the use of transactiontemplate. Declarative transaction management is built on the AOP. The essence is to intercept the method before and after it, and then create or join a transaction before the target method starts, committing or rolling back the transaction according to execution after the target method is executed. The greatest advantage of declarative transactions is that you do not need to programmatically manage transactions, so that you do not need to doping transaction-managed code in your business logic code, just make relevant transaction rule declarations in the configuration file (or through @transactional annotations). You can apply transaction rules to the business logic.

It is obvious that declarative transaction management is better than programmatic transaction management, which is the non-intrusive development approach advocated by spring. Declarative transaction management makes business code non-polluting, a common Pojo object that can be fully transactional supported with annotations. The only disadvantage of declarative transactions, compared to programmatic transactions, is that the finer granularity of the latter only works at the method level and cannot be scoped to the code block as a programmatic transaction. But even with this requirement, there are many workarounds, such as the ability to separate code blocks that require transaction management into methods, and so on. There are two common ways of declarative transaction management, one is an XML configuration file based on the TX and AOP namespaces, and the other is based on @transactional annotations. Obviously the annotation-based approach is easier to use and more refreshing

1.2. Spring Transaction rollback rules

The recommended way to instruct the spring transaction manager to roll back a transaction is to throw an exception within the context of the current transaction. The spring transaction manager catches any unhandled exceptions, and then determines whether the transaction that throws the exception is rolled back according to the rule. By default, spring rolls back the transaction only if the exception is thrown as a run-time unchecked exception, which is the subclass of RuntimeException that throws the exception (errors also causes the transaction to be rolled back), while throwing a checked exception does not cause the transaction to be rolled back. Can be explicitly configured to roll back transactions when those exceptions are thrown, including checked exceptions. You can also explicitly define those exceptions that are thrown without rolling back the transaction. You can also programmatically use the Setrollbackonly () method to indicate that a transaction must be rolled back, and that the only action you can perform after the call to Setrollbackonly () is to rollback.

@Transactional the location of the callout
@Transactional Annotations can be labeled on classes and methods, or on defined interfaces and interface methods.
If we annotate @Transactional annotations on the interface , this is a hidden hazard: Because annotations cannot be inherited, the @Transactional that are labeled in the business interface annotations are not inherited by the business implementation class. Therefore, there may be cases where the transaction does not start. So, spring suggests that we put @transaction annotations on the implementation class.
the @transactional annotation on the method overrides the @transactional on the class.

1.3. Steps to use


Step one, introduce namespaces in the spring configuration file

Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-2.0.xsd ">

Step two, beans with @transactional annotations are automatically configured for declarative transaction support

    <</span>bean id= "Defaulttransactionmanager" class= " Org.springframework.orm.hibernate3.HibernateTransactionManager ">        <</span>property name=" Sessionfactory "ref=" sessionfactory "/>    </</span>bean>           <</span>tx: Annotation-driven transaction-manager= "Defaulttransactionmanager" proxy-target-class= "true"/>

Step three, in the interface or class declaration, write a @transactional.
If only write on the interface, the implementation of the interface class will inherit, the interface implementation of the specific method of the class, you can override the settings at the class declaration
@Transactional //class-level annotations, methods that apply to all public in a class

ii. communication behavior and isolation level of the transaction

When you use spring's annotated transaction management, the propagation behavior and isolation level of the transaction may be a bit overwhelming, as detailed below for easy access.

How to annotate things: @Transactional

When marked in front of a class, all methods in the marked class are handled by the object

When certain methods in a class do not require things:

@Transactionalpublic class Testservicebean implements Testservice {       private Testdao dao;       public void Setdao (Testdao dao) {        This.dao = DAO;    }       @Transactional (propagation = propagation.not_supported) public    Listgetall () {return null;}}

Introduction to the act of spreading things:
@Transactional (propagation=propagation.required)
If there is a transaction, then join the transaction and create a new one (by default)
@Transactional (propagation=propagation.not_supported)
Container does not open transactions for this method
@Transactional (propagation=propagation.requires_new)
Creates a new transaction regardless of whether a transaction exists, the original hangs, the new execution completes, and the old transaction continues
@Transactional (Propagation=propagation.mandatory)
Must be executed in an existing transaction, or throw an exception
@Transactional (Propagation=propagation.never)
Must be executed in a non-transaction, otherwise throws an exception (as opposed to propagation.mandatory)
@Transactional (Propagation=propagation.supports)
If the other bean calls this method and declares the transaction in another bean, the transaction is used. If the other bean does not declare the transaction, then there is no transaction.

Things timeout settings:
@Transactional (timeout=30)//default is 30 seconds

Transaction ISOLATION Level:
@Transactional (isolation= isolation.read_uncommitted)
READ UNCOMMITTED data (dirty read, non-repeatable read) basic not used
@Transactional (isolation = isolation.read_committed)
Read committed data (non-repeatable read and Phantom reads occur)
@Transactional (isolation = isolation.repeatable_read)
REPEATABLE READ (phantom read occurs)
@Transactional (isolation = isolation.serializable)
Serialization

MYSQL: Default to Repeatable_read level
SQL Server: Default is read_committed

Dirty Read : One transaction reads uncommitted update data to another transaction
non-repeatable read : In the same transaction, multiple reads of the same data return different results, in other words,
Subsequent reads can be read to the updated data submitted by another transaction. Conversely, "repeatable reads" are repeated in the same transaction
When reading data, it is guaranteed to read the same data, that is, subsequent reads cannot be read to another transaction committed update data
Phantom Reading : One transaction reads the insert data that has been committed by another transaction

Description of common parameters in @Transactional annotations

parameter name

function description

readonly

Continuation form)

Parameter name

Function description

Rollbackforclassname

This property is used to set an array of exception class names that need to be rolled back, and when the method throws an exception in the specified exception name array, the transaction is rolled back. For example:

Specify a single exception class name: @Transactional (rollbackforclassname= "RuntimeException")

Specify multiple Exception class names: @Transactional (rollbackforclassname={"RuntimeException", "Exception"})

Norollbackfor

This property is used to set an array of exception classes that do not need to be rolled back, and when a method throws an exception in the specified exception array, the transaction is not rolled back. For example:

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

Specify multiple exception classes: @Transactional (Norollbackfor={runtimeexception.class,exception.class})

Norollbackforclassname

This property is used to set an array of exception class names that do not need to be rolled back, and when a method throws an exception in the specified exception name array, the transaction is not rolled back. For example:

Specify a single exception class name: @Transactional (norollbackforclassname= "RuntimeException")

Specify multiple exception class names:

@Transactional (norollbackforclassname={"RuntimeException", "Exception"})

Propagation

This property is used to set the propagation behavior of a transaction, which can be referenced in table 6-7.

Example: @Transactional (propagation=propagation.not_supported,readonly=true)

Isolation

This property is used to set the transaction isolation level of the underlying database, which is used to handle multi-transaction concurrency, usually using the default isolation level of the database, and does not need to be set

Timeout

This property is used to set the time-out seconds for a transaction, and the default value is 1 to never time out


third, the matters needing attention

1 @Transactional can only be applied to the public method, and for other non-public methods, if the @transactional is marked with no error, However, the method does not have transactional capabilities.

2 with the Spring transaction manager, Spring is responsible for opening, committing, and rolling back the database. The default run-time exception is encountered (the throw newruntimeexception ("comment");) is rolled back, That is, when an exception is encountered that is not checked (unchecked), and the exception that is caught (thrownewexception ("note");) is not rolled back, the exception that is checked is encountered (that is, the exception that is thrown at the non-runtime). When the compiler checks for an exception that is called a check exception or is checked for exceptions, we specify the way to let the transaction roll back, adding @transactional (Rollbackfor={exception.class, other exceptions}) to all exceptions. If you let unchecked exception do not roll back: @Transactional (Notrollbackfor=runtimeexception.class)
as follows:
@Transactional (rollbackfor= Exception.class)//Specify ROLLBACK, rollback
public void MethodName () {
throw new Exception ("comment") when an exception Exception is encountered;

}
@Transactional (norollbackfor=exception.class)//Specifies no rollback and encounters a run-time exception (Thrownew runtimeexception ("note");) rolls back the
Public Itimdaoimpl Getitemdaoimpl () {
throw new RuntimeException ("comment");
}

3. @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.


4. @Transactional annotations can be applied to interface definitions and interface methods, class definitions, and public methods of classes. Note, however, that the mere presence of @transactional annotations is not enough to open a transactional behavior, it is simply a meta-data that can be used to identify @Transactional annotations and beans that are configured appropriately for transactional behavior. In the above example, it is the presence of the element that opens the transaction behavior.


5. 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.


Spring transaction management-Configuring transactions with annotations

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.