Spring declarative Transaction Management example -- MyBatis study note sixteen

Source: Internet
Author: User

In this series of articles "examples of integration of MyBatis and Spring", we introduce Spring's programmatic transaction management. Dabing69221, a netizen, introduced the declarative transaction management integrated with MyBatis and Spring. Today, based on this knowledge point, we have improved the above example.

Spring declarative transaction management is implemented using AOPAspect-Oriented Programming for Aspect-Oriented Programming. In programming transaction management, the transaction processing code is actually similar, which leads to code duplication. In addition, programming transaction management can cause coupling between the transaction management code and the managed code, it does not meet the requirements of "high cohesion and low coupling" in software engineering. If AOP is used, the above defects can be avoided.

For jar packages to be introduced by Spring AOP, see http://blog.csdn.net/a352193394/article/details/7588851.

First, write a DAO class. The Code is as follows:

Package com. abc. dao; import com. abc. mapper. studentMapper; import com. abc. domain. student; public class StudentDao {private StudentMapper studentMapper; // setter and getter methods of studentMapper public void setStudentMapper (StudentMapper studentMapper) {this. studentMapper = studentMapper;} public StudentMapper getStudentMapper () {return this. studentMapper;} public void save (Student student) {this. studentMapper. add (student); int a = 1/0 ;}}

In this class, there is a save method for saving students, of course, you can also add other methods.

Next, we will apply the methods like AOP in Spring to provide transaction management. The configuration is as follows: beans. xml ):

<? Xml version = "1.0" encoding = "utf8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0. Xsdhttp: // www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/ Tx/spring-tx-3.0.xsd "default-autowire =" byName "default-lazy-init =" false "> <! -- In this example, the DBCP connection pool is used. Copy the jar package of DBCP to the lib directory of the project in advance. The connection pool configuration is as follows --> <bean id = "dataSource" class = "org. apache. commons. dbcp. basicDataSource "> <property name =" driverClassName "value =" com. mysql. jdbc. driver "/> <property name =" url "value =" jdbc: mysql: // localhost/courseman "/> <property name =" username "value =" courseman "/> <property name =" password "value =" abc123 "/> </bean> <bean id = "sqlSessionFactory" class = "org. mybatis. spring. sqlSessionFactoryBean "> <! -- DataSource attribute specifies the connection pool to be used --> <property name = "dataSource" ref = "dataSource"/> <! -- ConfigLocation attribute specifies the core configuration file of mybatis --> <property name = "configLocation" value = "resources/configuration. xml "/> </bean> <bean id =" transactionManager "class =" org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "/> </bean> <bean id =" parentMapper "class =" org. mybatis. spring. mapper. mapperFactoryBean "abstract =" true "> <! -- SqlSessionFactory attribute specifies the SqlSessionFactory instance to be used --> <property name = "sqlSessionFactory" ref = "sqlSessionFactory"/> </bean> <bean id = "studentMapper" parent = "parentMapper "> <! -- MapperInterface attribute specifies the ER interface, which is used to implement this interface and generate the er object --> <property name = "mapperInterface" value = "com. abc. mapper. studentMapper "/> </bean> <! -- Inject studentMapper into studentDao --> <bean id = "studentDao" class = "com. abc. dao. studentDao "> <property name =" studentMapper "ref =" studentMapper "/> </bean> <! -- Configure the transaction processing policy and specify the transaction manager in the transaction-manager attribute. If the transaction manager bean id is transactionManager, you can leave the transaction-manager attribute unspecified --> <tx: advice id = "txAdvice" transaction-manager = "transactionManager"> <tx: attributes> <! -- All Methods Starting with find are read-only --> <tx: method name = "find *" read-only = "true"/> <tx: method name = "save *"/> <! -- Use the default transaction policy for other methods --> <tx: method name = "*"/> </tx: attributes> </tx: advice> <! -- AOP configuration --> <aop: config> <! -- The pointcut element defines an entry point. The first asterisk in execution is used to match the return type of the method. The asterisk indicates that all return types are matched. Com. abc. dao. *. *(..) com. abc. all methods of all classes under the dao package --> <aop: pointcut id = "myPointcut" expression = "execution (* com. abc. dao. *. *(..)) "/> <! -- Apply the defined transaction processing policy to the preceding entry point --> <aop: advisor advice-ref = "txAdvice" pointcut-ref = "myPointcut"/> </aop: config> </beans>

As shown above, the configuration of the transaction policy is mainly the configuration of the <tx: method/> label. The name attribute is required to specify the target method of the transaction policy. In addition to the read-only attribute, there are attributes such as propagation and rollback-for to specify the propagation attribute of the transaction and to trigger the exception of transaction rollback. The rollback-for attribute is not specified here. By default, Spring rolls back the transaction only when a RuntimeException or Error exception occurs.

The execution expression is displayed in the <aop: pointcut/> configuration. For how to write this expression, see http://lavasoft.blog.51cto.com/62575/172292 /.

In the save method of StudentDao, a row of code int a = 1/0 is intentionally added. This line of code throws the ArithmeticException, which is a RuntimeException). According to the above configuration, Spring will roll back the transaction. Shows the execution result:

650) this. width = 650; "title =" running result .png "src =" http://www.bkjia.com/uploads/allimg/131228/11310M3U-0.png "/>

As shown in, the transaction has been rolled back, queried in the database, and student records have not been inserted.

Download the source code in this example: http://down.51cto.com/data/857171.

MyBatis Study Notes series I: download and install ant

Prepare for MyBatis Study Notes Series II: ant getting started

MyBatis learning notes: MyBatis getting started

MyBatis Study Notes Series II: Example of adding, deleting, and modifying MyBatis

MyBatis Study Notes Series 3: association examples of MyBatis

MyBatis Study Notes Series 4: two forms of MyBatis association

MyBatis Study Notes Series 5: examples of integration between MyBatis and Spring

MyBatis Study Notes Series 6: examples of integration between MyBatis and Spring

MyBatis study notes 7: MyBatis one-to-multiple bidirectional Association

MyBatis Study Notes: MyBatis MapperScannerConfigurer Configuration

MyBatis Study Notes: two forms of MyBatis collection

MyBatis Study Notes Series 10: Log4j example of MyBatis logs

MyBatis Study Notes: example of how to annotate MyBatis with multiple parameters

MyBatis learning notes: Example of the default naming method for MyBatis multi-parameter transfer

MyBatis Study Notes: Example of Map mode for MyBatis multi-parameter transfer

MyBatis Study Notes: N + 1 in MyBatis

MyBatis Study Notes: a hybrid transfer of multiple parameters in MyBatis

MyBatis Study Notes:Spring declarative Transaction Management example

MyBatis Study Notes:Example of MyBatis multi-to-multiple storage

This article is from the "Xiao fan's column" blog, please be sure to keep this source http://legend2011.blog.51cto.com/3018495/1239139

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.