SSM framework--Implementing transaction management in annotation form

Source: Internet
Author: User
Tags aop rollback

The Last Post, "The SSM three framework Integration detailed tutorial" details how to integrate the spring, SPRINGMVC and MyBatis these three broad frameworks. But there is no mention of how to configure MyBatis transaction management to implement development, and transactions are essential. This article, as a supplement to the previous article, explains how to use annotations in the SSM framework for transaction management.


what is a transaction.

In the process of writing a business, a transaction is required, and when multiple INSERT statements are required, if the first few succeed, and the last fails, then we need to roll back the database operations to maintain the consistency and integrity of the data, and at this point we need to take advantage of the DB transaction processing. A transaction is the basic unit of recovery and concurrency control.


In short, the so-called transaction is a sequence of operations, which are either executed or not executed, and it is an indivisible unit of work.


Transactions should have 4 properties: atomicity, consistency, isolation, persistence. These four properties are commonly referred to as ACID properties.


 Atomic sex (atomicity). A transaction is an indivisible unit of work, and all operations included in the transaction are either done or not done.


 Consistency (consistency). The transaction must be to change the database from one consistency state to another. Consistency is closely related to atomicity.


 Isolation (Isolation). Execution of a transaction cannot be interfered by other transactions. That is, the operations within a transaction and the data used are isolated from other concurrent transactions, and the transactions performed concurrently cannot interfere with each other.


 Persistence (Durability). Persistence is also called permanence (permanence), meaning that once a transaction is committed, its changes to the data in the database should be permanent. The rest of the operation or failure should not have any effect on it.


MyBatis Integrated Spring transaction Management

In the SSM framework, spring's transaction management mechanism is used. Spring can implement transactions programmatically, declaratively implement transactions, and annotate implementations of transactions. This article is mainly about how to implement transaction management with the annotation-type @transanctional.


This article code example is based on the previous blog post, the specific code "SSM three major framework integration detailed tutorial" has been given. Simply look at the directory structure and entity classes:



1. Configure Spring-mybatis.xml Files

To implement transaction management in the form of annotations, simply add the following code to the configuration file:


<!--turn on transaction annotation driver-->
	<tx:annotation-driven/>
	<!--(transaction management) transaction manager, use Jtatransactionmanager for global TX-->
	<bean id= "TransactionManager"
		Org.springframework.jdbc.datasource.DataSourceTransactionManager ">
		<property name=" DataSource "ref=" DataSource "/>
	</bean>

Of course, if an error occurs at this time, the document structure cannot be recognized because of the absence of xmlns and schema. The introduction of the header file can be, the following is mine, according to their own needs to introduce:


<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:p=" http://www.springframework.org/schema/p "xmlns:context=" http:// Www.springframework.org/schema/context "xmlns:aop=" Http://www.springframework.org/schema/aop "xmlns:mvc=" http:// Www.springframework.org/schema/mvc "xmlns:tx=" Http://www.springframework.org/schema/tx "xmlns:jdbc=" http://  
                        Www.springframework.org/schema/jdbc "xsi:schemalocation=" Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans-3.1.xsd Http://www.springframewor
                        K.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd  
    					Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/SPRING-AOP-3.0.xsd Http://www.springframework.org/schema/mvc HTTP://WWW.SPRINGFR Amework.org/schema/mvc/spring-mvc-4.0.xsd ">



2. How to use


Use a small example here to test whether the transaction management was successfully configured. The code base is the SSM framework to build the test code inside. The methods we are now testing are: I want to insert a collection of user objects that can be inserted successfully if the number of this object is less than 2, but if greater than 2, throw an exception (the transaction must throw an exception so that spring will help the transaction rollback) so that the database rolls back without inserting any data. Test results if the database does not insert any data, then the transaction configuration is successful, anyway, failed.

Note that @transactional can only be applied to the public method, and for other non-public methods, a @transactional is not an error if it is marked, but the method has no transactional functionality.


entity classes, DAO interfaces, business interfaces, and business implementations, this test only needs to add a method to the business layer, and then use the JUnit test to add the following method to the business implementation class, noting the annotation @transactional:

/**
	 * Transaction processing must throw an exception, spring will help transaction rollback
	 * @param users/
	
	@Transactional @Override
	public
	Void Insertuser (list<user> users) {
		//TODO auto-generated method stub for
		(int i = 0; i < users.size (); i++) {
			if (i<2) {
				This.userDao.insert (Users.get (i));
			}
			else {
				throw new RuntimeException ();}}}
	

Next, add the following methods to test the test class:


@Test public
	void Testtransaction () {
		list<user> users = new arraylist<user> ();
		for (int i=1;i<5;i++) {
			User user = new user ();
			User.setage (i);
			User.setpassword (i+ "111111");
			User.setusername ("test" +i);
			Users.add (user);
		}
		This.userService.insertUser (users);
	}


Note: The JUnit test will find an error at this point because the exception is thrown in the method. In essence, transaction management is done, the data is not inserted, the configuration is successful, and if the annotation is removed, the first two data will be inserted successfully, and then the exception will be thrown later.


(Original address: Http://blog.csdn.net/zhshulin)

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.