Spring transaction configuration, spring transaction

Source: Internet
Author: User

Spring transaction configuration, spring transaction

1. Configure txManager first.

The following dataSource is the data connection pool. The corresponding connection pool is configured according to project requirements.

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean>

2. Use the @ Transactional annotation to use transactions.

<tx:annotation-driven transaction-manager="txManager"/>

Usage (enable bean scan configuration ):

When marked before the class, all methods in the class are processed

Example:

@Transactionalpublic class PersonServiceBean implements PersonService {}

When some methods in the class do not require things:

@Transactionalpublic class TestServiceBean implements TestService {        @Transactional(propagation = Propagation.NOT_SUPPORTED)    public List<Object> getAll() {        return null;    }    }

3. Configure transactions in XML-based mode

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><aop:config><aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/></aop:config><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/><tx:method name="*"/></tx:attributes></tx:advice>

 

4. Indicator

* Any wildcard

Expression = "execution (* cn. itcast. service .. *. *(..)) "indicates the role in cn. itcast. all methods of all classes under the service package and sub-Package

Expression = "execution (* cn. itcast. service .. *. * (java. lang. string ,..)) "indicates the role in cn. itcast. the first parameter of the service package and all classes under the sub-package is the String type method.

Expression = "execution (java. lang. string cn. itcast. service .. *. *(..)) "indicates the role in cn. itcast. the Return Value Type of all classes in the service package and sub-package is String.

Expression = "execution (! Java. lang. string cn. itcast. service .. *. *(..)) "indicates the role in cn. itcast. the Return Value Type of all classes in the service package and sub-package is not on all methods of String.

Expression = "execution (* set ** (..)" indicates that the function is applied to any method starting with set.

Within-specifies a connection point that matches a specific type

Expression = "winthin (cn. itcast. *)" indicates all connection points under the cn. itcast package and the sub-package.

 

5. Introduction to promotional activities: 

@ Transactional (propagation = Propagation. REQUIRED)
If a transaction exists, add it to the transaction. If no transaction exists, create a new one (by default)
@ Transactional (propagation = Propagation. NOT_SUPPORTED)
The container does not enable transactions for this method.
@ Transactional (propagation = Propagation. REQUIRES_NEW)
No matter whether a transaction exists or not, a new transaction is created, the original transaction is suspended, the new execution is completed, and the old transaction continues to be executed.
@ Transactional (propagation = Propagation. MANDATORY)
Must be executed in an existing transaction; otherwise, an exception is thrown.
@ Transactional (propagation = Propagation. NEVER)
Must be executed in a transaction that does not exist; otherwise, an exception is thrown (opposite to Propagation. MANDATORY)
@ Transactional (propagation = Propagation. SUPPORTS)
If other beans call this method and declare transactions in other beans, use transactions. If other beans do not declare transactions, no transactions are required.

 

Transaction timeout settings:
@ Transactional (timeout = 30) // The default value is 30 seconds.

 

Transaction isolation level:
@ Transactional (isolation = Isolation. READ_UNCOMMITTED)
Read uncommitted data (dirty reads may occur and repeated reads are not allowed ).
@ Transactional (isolation = Isolation. READ_COMMITTED)
Read committed data (non-repeated and phantom read will occur)
@ Transactional (isolation = Isolation. REPEATABLE_READ)
Repeatable read (phantom read will occur)
@ Transactional (isolation = Isolation. SERIALIZABLE)

Serializing

 

MYSQL: REPEATABLE_READ level by default
SQLSERVER: READ_COMMITTED by default

Dirty read: One Transaction reads uncommitted update data from another transaction

Non-repeated read: In the same transaction, the results returned by reading the same data are different for multiple times. In other words, you can read the updated data committed by another transaction later. on the contrary, when "Repeatable read" reads data multiple times in the same transaction, it can ensure that the read data is the same, that is, subsequent reads cannot read the updated data committed by another transaction.

Phantom read: One Transaction reads the insert data committed by another transaction

 


How can I configure spring transactions?

---------------------------------------------------------

Spring provides two types of transaction management: programmatic and declarative.

Programming, flexible, but with a large amount of code, there are more repeated code; declarative is more flexible and convenient than programming.

1. Traditional JDBC Transaction Management

In the past, JDBC was used for data operations and DataSource was used to obtain the Connection from the data source. We know that the data source is thread-safe, and the Connection is not thread-safe, therefore, a new connection is retrieved from the data source for each request. Generally, data sources are managed by containers, including connection pools. For example, TOMCAT, WEBSPHERE, WEBLOGIC, and other J2EE commercial containers provide this function.

In the past, when we used JDBC to write code, transaction management may be like this:

Connection conn = null;
Try {
Conn = DBConnectionFactory. getConnection;
Conn. setAutoCommit (false );
// Do something
Conn. commit (); // commit transcation
} Catch (Exception e ){
Conn. rollback ();
}
Finally {
Try {
Conn. close ();
} Catch (SQLException se) {// do something .}
// Close ResultSet, PreparedStatement, Connection
// Notice: Maybe ocurr Exception when u close rs, pstmt, conn
}

Write the code according to the previous ideas. The Code volume is long, and it is easy to neglect. Forget some try/catch, and cause some exceptions that cannot be caught. Although sometimes we will write the DBTool class, to close these resources, and ensure that no exception is thrown to the outside when these resources are closed, but this will cause extra trouble.

2. Programming transaction processing provided by Spring

Spring provides several transaction processing classes: TransactionDefinition // transaction attribute Definition

TranscationStatus // indicates the current transaction, which can be committed and rolled back.

PlatformTransactionManager is the basic interface provided by spring for managing transactions. There is an implementation abstract class AbstractPlatformTransactionManager under it. The transaction management class we use, such as cetcetransactionmanager, is a subclass of this class.

The procedure of using a programmatic transaction management process may be as follows:

(1) Declare the data source.

(2) declare a transaction management class, such as DataSourceTransactionManager, HibernateTransactionManger, and JTATransactionManager.

(3) Add the transaction processing code to our code:

TransactionDefinition td = new TransactionDefinition ();
TransactionStatus ts = transactionManager. getTransaction (td );
Try {
/<G id = "1"> </G>

How to configure things in spring

Five Spring transaction configuration methods
Some time ago, I made a deep research on Spring transaction configuration. Although I have also configured Spring transaction configuration, I have never understood it clearly. Through this study, we found that Spring's transaction configuration should be well understood as long as the idea is clarified.
Summary:

The transaction configuration in the Spring configuration file is always composed of three parts: DataSource, TransactionManager, and proxy mechanism. In any configuration method, the agent mechanism is changed.

DataSource and TransactionManager only change according to the data access method. For example, when Hibernate is used for data access, DataSource is actually SessionFactory, and the implementation of TransactionManager is HibernateTransactionManager.

For example:

According to different proxy mechanisms, Five Spring transaction configuration methods are summarized. The configuration file is as follows:

Method 1: Each Bean has a proxy

<? Xml version = "1.0" encoding = "UTF-8"?>
<Beans xmlns = "www.springframework.org/schema/beans"
... ">

<Bean id = "sessionFactory"
Class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean">
<Property name = "configLocation" value = "classpath: hibernate. cfg. xml"/>
<Property name = "configurationClass" value = "org. hibernate. cfg. AnnotationConfiguration"/>
</Bean>

<! -- Define the Transaction Manager (declarative transaction) -->
<Bean id = "transactionManager"
Class = "org. springframework. orm. hibernate3.HibernateTransactionManager">
<Property name = "sessionFactory" ref = "sessionFactory"/>
</Bean>

<! -- Configure DAO -->
<Bean id = "userDaoTarget" class = & quo ...... full text>

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.