Spring implements a simple transaction management

Source: Internet
Author: User

The first two days to the company's database operations added transaction management, today's blog is more of this bar.

First of all: This article is simply to implement the transaction, the specific content of the transaction, such as the level of transactions, the specific implementation of the principle and so on ... Rookie level is limited, temporarily not even this, the future blog may be involved.

If you can simply implement a transaction after reading this blog, the purpose of this article is achieved.

First of all, a simple and popular explanation of what is called a transaction: all the operations of the database in a method of the statement, or all the execution (the method is not error), or all do not execute (the method is thrown wrong, the statement has been executed rollback).

Implementing transactions in XML form is also a transaction that I implement in my company code. His advantage is that there is no need to make any changes to the existing code, which is more appropriate for this post-accession transaction management, and the disadvantage is that the XML file can be large.

The following are the individual information in the XML:

<location= "Classpath:jdbc.properties"/>

This statement is used to read the configuration file (user name password for the database, etc.)

<proxy-target-class= "true"></aop:config> 

Force the use of Cglib agent (temporarily do not know why, do not add this sentence my code will error)

<BeanID= "DataSource"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close">        < Propertyname= "Defaultautocommit"value= "true" />        < Propertyname= "Driverclassname"value= "${driverclassname}" />        < Propertyname= "url"value= "${url}" />        < Propertyname= "username"value= "Umetrip" />        < Propertyname= "Password"value= "${password}" />    </Bean>

Data source, not explained!

<id= "TransactionManager"        class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager ">        <   name= "DataSource"  ref= "DataSource"/>     </Bean>

Registers a transaction and specifies the data source for the transaction

<!--Register database operation Class--
<BeanID= "Testdao"class= "TestSpring.business.Dao.iface.impl.TestDaoImpl">        < Propertyname= "DataSource"ref= "DataSource" />    </Bean>    <BeanID= "DbTest1"class= "TestSpring.business.transaction.DbTest1">        < Propertyname= "Testdao"ref= "Testdao" />    </Bean><Aop:config>        <Aop:pointcutID= "Transactionpointcut"expression= "Execution (* TestSpring.business.Dao.iface.impl). *.*(..))" />        <Aop:advisorAdvice-ref= "Txadvice"Pointcut-ref= "Transactionpointcut" />    </Aop:config>

The entry point for the registration transaction. As you can see, transactions are taking advantage of facets in spring to inject transaction management into the method.

Where expression= "Execution (* TestSpring.business.Dao.iface.impl).  *.*(..)) :

1. Execution (): The body of an expression.

2, the first * Number: Indicates the return type, the * number denotes all types.

3. Package Name: Indicates the package name that needs to be intercepted, and the following two periods represent all the child packages of the current package and the current package, Com.sample.service.impl the package, and the descendants of all classes.

4, the second * Number: denotes the class name, the * number denotes all classes.

5, * (..): The last asterisk denotes the method name, the * number denotes all methods, the following parentheses indicate the parameters of the method, and two periods represent any parameters.

<Tx:adviceID= "Txadvice"Transaction-manager= "TransactionManager">        <tx:attributes>            <!--If the method is a method that starts with get, the transaction is not used -            <Tx:methodname= "get*"read-only= "true"Propagation= "not_supported" />            <!--all other methods in a class use transaction management -            <Tx:methodname="*" />        </tx:attributes>    </Tx:advice>

Specify the manager for the transaction and configure the transaction information.

Just configure the XML file, and the code does not have to be modified.

Test code:

// Read the configuration file (load the bean in the configuration file into memory)        New Classpathxmlapplicationcontext ("/testspring/resources/applicationcontext_transaction.xml");         // gets the instance          DbTest1 bean = (DbTest1) ctx.getbean ("DbTest1");           // calling methods          Try {            bean.test ();        } Catch (Exception e) {            e.printstacktrace ();        }

Testdaoimpl class:

 PackageTestSpring.business.Dao.iface.impl;ImportJavax.sql.DataSource;Importorg.springframework.jdbc.core.JdbcTemplate;Importorg.springframework.transaction.annotation.Propagation;Importorg.springframework.transaction.annotation.Transactional;ImportTestSpring.business.Dao.iface.ITestDao;ImportTestSpring.business.bean.TableBean;/*** Itestdao.java: *@authorXuejupo [email protected] * Create in 2016-2-16 pm 5:04:56*/ Public classTestdaoimplImplementsitestdao{PrivateJdbcTemplate JdbcTemplate;  Public voidSetdatasource (DataSource DataSource) { This. jdbctemplate=NewJdbcTemplate (DataSource); } @Override Public voidAdd (Tablebean user) {//TODO auto-generated Method StubJdbctemplate.update ("INSERT into test values (?,?)",NewObject[]{user.getid (), User.getname ()});  This. del (1); Jdbctemplate.update ("Delete from Test where id =?",Newobject[]{213123,2}); } @Override Public voidDelintID) {//TODO auto-generated Method StubJdbctemplate.update ("Delete from Test where id =?",NewObject[]{id}); }}

Modify the Add code of the Testdaoimpl class several times and perform the result discovery: If an exception is thrown by the Add method, all SQL statements within the Add method are rolled back. However, if no exception occurs within the Add method or the exception is handled, the SQL statement that the Add method has executed will be committed.


1. The transaction is for a method, as long as the error is thrown in this method, all database operations within this method are rolled back (for example, the Del method in the Add method in the above class will also be rolled back).

2. The current method transaction is invalid if the exception is caught in the transaction management method and is written to log without being thrown out ... The workaround is to throw an exception outward after writing to log.

3. The transaction is very complex. Don't look at it as simple as it says. For example, the isolation level of a transaction, the level of lock table for a transaction (row or table lock, and whether the index is locked or not).

PS: If you see a blog that is not my blog (bot Zombie blog), Welcome to my blog to discuss with me: http://www.cnblogs.com/xuejupo/

Spring implements a simple transaction management

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.