Spring Transaction Management

Source: Internet
Author: User

Configure the environment, import the appropriate jar package: Ioc/aop/jdbctemplate/c3p0 the corresponding jar package for the connection pool

The program outlines: Create a database

Table structure:

Two methods in DAO, Lesssalary (), moresalary () are used to simulate transfers,

Then call the two methods in DAO in the service to complete the transfer operation

One. Do not use transactions:

11 PackageOrg.dao;2233Importorg.springframework.jdbc.core.JdbcTemplate;445566 Public classDao {77Privatejdbctemplate JdbcTemplate;8899 Public voidsetjdbctemplate (JdbcTemplate jdbctemplate) {Ten10 This. JdbcTemplate =JdbcTemplate; One11     } A12 -13//Xiao Wang transfer to pony amount -14 Public voidlesssalary () { the15//TODO auto-generated Method Stub -String sql= "Update Acountmoney set salary=salary+? where Name=? "; -Jdbctemplate.update (sql,-2000, "Xiao Wang");  -18     } +19 -20 Public voidmoresalary () { +21st//TODO auto-generated Method Stub AString sql= "Update Acountmoney set salary=salary+? where Name=? "; atJdbctemplate.update (sql,2000, "Pony");; -24     } -25 -26}

1  PackageOrg.service;2 3 ImportOrg.dao.Dao;4 5  Public classService {6     PrivateDAO DAO;7 8      Public voidsetdao (dao dao) {9          This. DAO =DAO;Ten     } One      Public voidchangesalary () { ASystem.out.println ("Start transfer .....") "); -          This. Dao.lesssalary (); -          This. Dao.moresalary (); theSYSTEM.OUT.PRINTLN ("Transfer success .....") "); -     } -}
1<?xml version= "1.0" encoding= "UTF-8"?>2<beans xmlns= "Http://www.springframework.org/schema/beans"3Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4xmlns:context= "Http://www.springframework.org/schema/context"5xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"6xmlns:tx= "Http://www.springframework.org/schema/tx"7Xsi:schemalocation= "Http://www.springframework.org/schema/beans8http//www.springframework.org/schema/beans/spring-beans.xsd9http//Www.springframework.org/schema/contextTenhttp//www.springframework.org/schema/context/spring-context.xsd Onehttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Ahttp//www.springframework.org/schema/aop/spring-aop.xsd -http//Www.springframework.org/schema/tx -http//www.springframework.org/schema/tx/spring-tx.xsd "> the<!--Configure C3P0 connection pool-- -<bean id= "C3p0"class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > -<property name= "Driverclass" value= "Com.mysql.jdbc.Driver" ></property> -<property name= "Jdbcurl" value= "Jdbc:mysql://localhost:3306/account" ></property> +<property name= "User" value= "root" ></property> -<property name= "Password" value= "jay571018" ></property> +</bean> A      at<!--creating a DAO object injection jdbctemplate--> -<bean id= "DAO"class= "Org.dao.Dao" > -<property name= "JdbcTemplate" ref= "JdbcTemplate" ></property> -</bean> -      -<!--Creating service object Injection dao--> in<bean id= "Service"class= "Org.service.Service" > -<property name= "DAO" ref= "DAO" ></property> to</bean> +      -<!--creating JdbcTemplate Object Injection Database connection pool-- the<bean id= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate" > *<property name= "DataSource" ref= "c3p0" ></property> $</bean>Panax Notoginseng      -</beans>
1  Packageorg.test;2 3 Importorg.junit.Test;4 ImportOrg.service.Service;5 ImportOrg.springframework.context.ApplicationContext;6 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;7 8  Public classTestsalary {9 @TestTen      Public voidtestsalary () { OneApplicationContext ac=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); AService s= (Service) Ac.getbean ("service"); - s.changesalary (); -     } the}

Program run Result: Xiao Wang to Pony Transfer 2000, the data in the database has been updated

The above code does not use transactions, but if during the transfer process, the

1      Public void changesalary () {2         System.out.println ("Start transfer .....") "); 3          This . Dao.lesssalary ();

A: An error has occurred here

4          This . Dao.moresalary (); 5         SYSTEM.OUT.PRINTLN ("Transfer success .....") "); 6     }

 1  public  void   Changesalary () { 2  System.out.println (" Start transfer ... " 3  this   4  int  t=10/0;   simulation exception  5  this  .dao.moresalary ();  6  System.out.println ("Transfer success ..... " 7 } 

Two. Use the transaction mechanism in the spring framework for processing (other local code does not need to change, just add the transaction in the configuration file, this is the charm of AOP)

1<?xml version= "1.0" encoding= "UTF-8"?>2<beans xmlns= "Http://www.springframework.org/schema/beans"3Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4xmlns:context= "Http://www.springframework.org/schema/context"5xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"6xmlns:tx= "Http://www.springframework.org/schema/tx"7Xsi:schemalocation= "Http://www.springframework.org/schema/beans8http//www.springframework.org/schema/beans/spring-beans.xsd9http//Www.springframework.org/schema/contextTenhttp//www.springframework.org/schema/context/spring-context.xsd Onehttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Ahttp//www.springframework.org/schema/aop/spring-aop.xsd -http//Www.springframework.org/schema/tx -http//www.springframework.org/schema/tx/spring-tx.xsd "> the<!--Configure C3P0 connection pool-- -<bean id= "C3p0"class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > -<property name= "Driverclass" value= "Com.mysql.jdbc.Driver" ></property> -<property name= "Jdbcurl" value= "Jdbc:mysql://localhost:3306/account" ></property> +<property name= "User" value= "root" ></property> -<property name= "Password" value= "jay571018" ></property> +</bean> A      at<!--creating a DAO object injection jdbctemplate--> -<bean id= "DAO"class= "Org.dao.Dao" > -<property name= "JdbcTemplate" ref= "JdbcTemplate" ></property> -</bean> -      -<!--Creating service object Injection dao--> in<bean id= "Service"class= "Org.service.Service" > -<property name= "DAO" ref= "DAO" ></property> to</bean> +      -<!--creating JdbcTemplate Object Injection Database connection pool-- the<bean id= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate" > *<property name= "DataSource" ref= "c3p0" ></property> $</bean>Panax Notoginseng      -<!--configuration Transaction Manager- the<bean id= "TransactionManager"class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > +<!--inject the data source, which is the C3p0 object above-- A<property name= "DataSource" ref= "c3p0" ></property> the</bean> +      -<!--configuring transaction enhancement, specifying the transaction manager to use, which is the transactionmanager--> configured above $<tx:advice id= "Txadvice" transaction-manager= "TransactionManager" > $<!--set up matching rules for methods that require transactional operations the Changesalary () method is transacted in this program (change* includes Changesalary)- -<tx:attributes> -<tx:method name= "Changesalary"/> the</tx:attributes> -</tx:advice>Wuyi      the<!--Configure the facets to use the enhancements to the specific method above the process-- -<aop:config> Wu<!--configuring Pointcuts-- -<aop:pointcut expression= "Execution (* org.service.service.* (..))" id= "P1"/> About<!--Specify the enhancements to use and the entry point of the app-- $<aop:advisor advice-ref= "Txadvice" pointcut-ref= "P1"/> -</aop:config> -      -</beans>

This way, even if an exception occurs at a, the data remains consistent through the rollback mechanism of the transaction.

So the role of transaction processing in database access is obvious.

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