spring的事务管理,本文的例子是:比如你需要网购一本书,卖书的那一方有库存量以及书的价格,你有账户余额。回想我们在编程中要实现买书这样的功能,由于你的账户表和书的库存量表肯定不是同一张数据库表,所以必定会有一个先后,要么先将账户余额扣除书的价格,紧接着将书的库存量减一,要么反过来。那么问题来了,假如我们先将你的账户余额减掉,然后发现书的库存不足,这时怎么办呢,这就需要事务了,当我们发现书的库存不足时就要回滚事务,将你的余额返回去。只要配置了事务,发生了异常,就回滚。这就是事务的回滚。注:新人理解,如有错误,望指正,谢谢。

配置文件applicationContext.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
  9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
  10.  
  11. <!-- 导入资源文件 -->
  12. <context:property-placeholder location="classpath:jdbc.properties"/>
  13.  
  14. <!-- 配置c3p0数据源 -->
  15. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  16. <property name="user" value="${user}"></property>
  17. <property name="password" value="${password}"></property>
  18. <property name="driverClass" value="${driverClass}"></property>
  19. <property name="jdbcUrl" value="${jdbcUrl}"></property>
  20.  
  21. <property name="initialPoolSize" value="${initPoolSize}"></property>
  22. <property name="maxPoolSize" value="${maxPoolSize}"></property>
  23. </bean>
  24.  
  25. <!-- 配置自动扫描的包 -->
  26. <context:component-scan base-package="spring"></context:component-scan>
  27.  
  28. <!-- 配置spring 的JdbcTemplate -->
  29. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  30. <property name="dataSource" ref="dataSource"></property>
  31. </bean>
  32.  
  33. <!-- 配置事务管理器 -->
  34. <bean id="transactionManager"
  35. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  36. <property name="dataSource" ref="dataSource"></property>
  37. </bean>
  38.  
  39. <!-- 启用事务注解 -->
  40. <tx:annotation-driven transaction-manager="transactionManager"/>
  41.  
  42. </beans>

applicationContext.xml

配置文件jdbc.propertices:

  1. user=root
  2. password=123
  3. driverClass=com.mysql.jdbc.Driver
  4. jdbcUrl=jdbc\:mysql\:///spring?encoding\=UFT-8
  5. initPoolSize=5
  6. maxPoolSize=20

BookShopDao.java:

  1. package spring.tx;
  2.  
  3. public interface BookShopDao {
  4.  
  5. public int findBookPriceByIsbn(String isbn);
  6. public void updataBookStock(String isbn);
  7. public void updataUserAccount(String username,int price);
  8. }

BookShopDaoImp.java:

  1. package spring.tx;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.jdbc.core.JdbcTemplate;
  5. import org.springframework.stereotype.Repository;
  6.  
  7. @Repository("bookShopDao")
  8. public class BookShopDaoImp implements BookShopDao {
  9.  
  10. @Autowired
  11. private JdbcTemplate jdbcTemplate;
  12.  
  13. @Override
  14. public int findBookPriceByIsbn(String isbn) {
  15. String sql = "select price from book where isbn=?";
  16. return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
  17. }
  18.  
  19. @Override
  20. public void updataBookStock(String isbn) {
  21. // 检查书的库存是否不够
  22. String sql1 = "select stock from book_stock where isbn=?";
  23. if (jdbcTemplate.queryForObject(sql1, Integer.class, isbn) <= 0) {
  24. throw new BookStockException("库存不足");
  25. }
  26. String sql = "update book_stock set stock=stock-1 where isbn=?";
  27. jdbcTemplate.update(sql, isbn);
  28. }
  29.  
  30. @Override
  31. public void updataUserAccount(String username, int price) {
  32. // 检查余额是否足够
  33. String sql1 = "select balance from account where username=?";
  34. if (jdbcTemplate.queryForObject(sql1, Integer.class, username) < price) {
  35. throw new UserAccountException("余额不足");
  36. }
  37. String sql = "update account set balance = balance - ? where username=?";
  38. jdbcTemplate.update(sql, price, username);
  39. }
  40.  
  41. }

BookShopDaoImp

BookShopService.java:

  1. package spring.tx;
  2.  
  3. public interface BookShopService {
  4. public void purchase(String username,String isbn);
  5. }

BookShopServiceImpl.java:

  1. package spring.tx;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.jdbc.core.JdbcTemplate;
  5. import org.springframework.stereotype.Repository;
  6.  
  7. @Repository("bookShopDao")
  8. public class BookShopDaoImp implements BookShopDao {
  9.  
  10. @Autowired
  11. private JdbcTemplate jdbcTemplate;
  12.  
  13. @Override
  14. public int findBookPriceByIsbn(String isbn) {
  15. String sql = "select price from book where isbn=?";
  16. return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
  17. }
  18.  
  19. @Override
  20. public void updataBookStock(String isbn) {
  21. // 检查书的库存是否不够
  22. String sql1 = "select stock from book_stock where isbn=?";
  23. if (jdbcTemplate.queryForObject(sql1, Integer.class, isbn) <= 0) {
  24. throw new BookStockException("库存不足");
  25. }
  26. String sql = "update book_stock set stock=stock-1 where isbn=?";
  27. jdbcTemplate.update(sql, isbn);
  28. }
  29.  
  30. @Override
  31. public void updataUserAccount(String username, int price) {
  32. // 检查余额是否足够
  33. String sql1 = "select balance from account where username=?";
  34. if (jdbcTemplate.queryForObject(sql1, Integer.class, username) < price) {
  35. throw new UserAccountException("余额不足");
  36. }
  37. String sql = "update account set balance = balance - ? where username=?";
  38. jdbcTemplate.update(sql, price, username);
  39. }
  40.  
  41. }

BookShopServiceImpl.java

Cashier.java:

  1. package spring.tx;
  2.  
  3. import java.util.List;
  4.  
  5. public interface Cashier {
  6. public void checkout(String username,List<String> isbns);
  7. }

CashierImpl.java:

  1. package spring.tx;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.transaction.annotation.Propagation;
  8. import org.springframework.transaction.annotation.Transactional;
  9.  
  10. @Service("cashier")
  11. public class CashierImpl implements Cashier {
  12.  
  13. @Autowired
  14. private BookShopService bookShopService;
  15.  
  16. @Transactional
  17. @Override
  18. public void checkout(String username, List<String> isbns) {
  19. for (int i = 0; i < isbns.size(); i++) {
  20. bookShopService.purchase(username, isbns.get(i));
  21. }
  22. }
  23.  
  24. }

CashierImpl

定义两个异常类:

  1. package spring.tx;
  2.  
  3. public class BookStockException extends RuntimeException{
  4.  
  5. /**
  6. *
  7. */
  8. private static final long serialVersionUID = 1L;
  9.  
  10. public BookStockException() {
  11. super();
  12. // TODO Auto-generated constructor stub
  13. }
  14.  
  15. public BookStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
  16. super(message, cause, enableSuppression, writableStackTrace);
  17. // TODO Auto-generated constructor stub
  18. }
  19.  
  20. public BookStockException(String message, Throwable cause) {
  21. super(message, cause);
  22. // TODO Auto-generated constructor stub
  23. }
  24.  
  25. public BookStockException(String message) {
  26. super(message);
  27. // TODO Auto-generated constructor stub
  28. }
  29.  
  30. public BookStockException(Throwable cause) {
  31. super(cause);
  32. // TODO Auto-generated constructor stub
  33. }
  34.  
  35. }

BookStockException

  1. package spring.tx;
  2.  
  3. public class UrAccountExceptionse extends RuntimeException {
  4.  
  5. /**
  6. *
  7. */
  8. private static final long serialVersionUID = 1L;
  9.  
  10. public UserAccountException() {
  11. super();
  12. // TODO Auto-generated constructor stub
  13. }
  14.  
  15. public UserAccountException(String message, Throwable cause, boolean enableSuppression,
  16. boolean writableStackTrace) {
  17. super(message, cause, enableSuppression, writableStackTrace);
  18. // TODO Auto-generated constructor stub
  19. }
  20.  
  21. public UserAccountException(String message, Throwable cause) {
  22. super(message, cause);
  23. // TODO Auto-generated constructor stub
  24. }
  25.  
  26. public UserAccountException(String message) {
  27. super(message);
  28. // TODO Auto-generated constructor stub
  29. }
  30.  
  31. public UserAccountException(Throwable cause) {
  32. super(cause);
  33. // TODO Auto-generated constructor stub
  34. }
  35.  
  36. }

UserAccountExceptionse

测试方法:

  1. package spring.tx.test;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.junit.Test;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;
  9.  
  10. import spring.tx.BookShopDao;
  11. import spring.tx.BookShopService;
  12. import spring.tx.Cashier;
  13.  
  14. public class SpringTransactionTest {
  15.  
  16. private ApplicationContext ctx=null;
  17. private BookShopDao bookShopDao;
  18. private BookShopService bookShopService;
  19. private Cashier cashier;
  20. {
  21. ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
  22. bookShopDao =(BookShopDao) ctx.getBean("bookShopDao");
  23. bookShopService=(BookShopService) ctx.getBean("bookShopService");
  24. cashier =(Cashier) ctx.getBean("cashier");
  25. }
  26.  
  27. @Test
  28. public void testTransactionPropagation(){
  29. List<String > isbns=new ArrayList<String>();
  30. isbns.add("1001");
  31. isbns.add("1002");
  32. cashier.checkout("aaa", isbns);
  33. }
  34.  
  35. @Test
  36. public void testBookShopService() {
  37. bookShopService.purchase("aaa", "1001");
  38. }
  39.  
  40. @Test
  41. public void testupdataBookStock(){
  42. bookShopDao.updataBookStock("1001");
  43. }
  44.  
  45. @Test
  46. public void testUpdataUserAccount(){
  47. bookShopDao.updataUserAccount("aaa", 200);
  48. }
  49.  
  50. @Test
  51. public void testBookShopDao(){
  52. int price=bookShopDao.findBookPriceByIsbn("1001");
  53. System.out.println(price);
  54.  
  55. }
  56. }

Spring初学之spring的事务管理注解的更多相关文章

  1. Spring初学之spring的事务管理xml

    所有的java类都是用的上一篇文章:Spring初学之spring的事务管理 不同的是,这时xml配置事务,所以就要把java类中的那些关于spring的注解都删掉,然后在xml中配置,Applica ...

  2. spring+mybatis之声明式事务管理初识(小实例)

    前几篇的文章都只是初步学习spring和mybatis框架,所写的实例也都非常简单,所进行的数据访问控制也都很简单,没有加入事务管理.这篇文章将初步接触事务管理. 1.事务管理 理解事务管理之前,先通 ...

  3. java框架之Spring(3)-JDBC模板使用&事务管理

    下面内容使用到的 jar 包下载 JDBC模板使用 入门 1.导包,如要导入 Spring 的基本开发包.数据库驱动包.Spring 提供的 JDBC 模板包,如下: 2.测试: @Test publ ...

  4. spring boot配置mybatis和事务管理

    spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...

  5. Spring 简单而强大的事务管理功能

    开始之前 关于本教程 本教程将深入讲解 Spring 简单而强大的事务管理功能,包括编程式事务和声明式事务.通过对本教程的学习,您将能够理解 Spring 事务管理的本质,并灵活运用之. 先决条件 本 ...

  6. 深入学习Spring框架(四)- 事务管理

    1.什么是事务? 事务(Transaction)是一个操作序列.这些操作要么都做,要么都不做,是一个不可分割的工作单位,是数据库环境中的逻辑工作单位.事务是为了保证数据库的完整性.例如:A给B转账,需 ...

  7. Spring—SSJ集成&声明式事务管理

    1.   课程介绍 1.  SSJ集成;(掌握) 2.  声明式事务管理;(掌握) 什么是三大框架 2.1.  ssh Struts/Struts2 Spring Hibernate 2.2.  ss ...

  8. Spring+JTA+Atomikos+mybatis分布式事务管理

    我们平时的工作中用到的Spring事务管理是管理一个数据源的.但是如果对多个数据源进行事务管理该怎么办呢?我们可以用JTA和Atomikos结合Spring来实现一个分布式事务管理的功能.了解JTA可 ...

  9. Spring MVC 中使用AOP 进行事务管理--注解实现

    注解实现实现事务管理很简单,和配置式差不多,配置文件的头文件也要加相应的支持.配置数据源,并开启事务管理支持即可. <bean id="transactionManager" ...

随机推荐

  1. IndiaHacks 2016 - Online Edition (CF) . D

    这题思路很简单,二分m,求最大流是否大于等于x. 但是比赛过程中大部分的代码都被hack了... 精度问题,和流量可能超int 关于精度问题,这题真是提醒的到位,如果是先用二分将精度控制在10^-8左 ...

  2. 二、docker入门

    docker入门 使用场景: 面向产品.面向开发.面向测试.面向运维.面向自动化.面向微服务.面向大规模的分布式架构(微信红包) 虚拟化解决方案: 商业解决方案: VMware vSphere,VMw ...

  3. 取得当前页面的value值问题

    取得当前输入input的值 <body>    <form action="">        <input type="text" ...

  4. C# MD5加密与校验 引用

    using System; using System.Security.Cryptography; using System.Text; class Example { // Hash an inpu ...

  5. php cmd 不能利用$_COOKIE 的处理 通过文件来暂存字符串

    路径 <?php define('CMDPATH', 'wD:\cmd\\'); echo CMDPATH; die(); broswer 路径无问题 w 读 用 <?php $wfile ...

  6. 【转】PowerVM 的主要组成部分及概念

    PowerVM 是在基于 IBM POWER 处理器的硬件平台上提供的具有行业领先水平的虚拟化技术家族.它是 IBM Power System 虚拟化技术全新和统一的品牌(逻辑分区,微分区,Hyper ...

  7. linux下tcpdump命令的使用

    一般情况下linux系统会自带tcpdump工具,如果系统没有安装,直接用命令安装就行了. 安装命令:yum install -y tcpdump 查看安装版本命令:tcpdump --help 查看 ...

  8. document write & close

    在载入页面后,浏览器输出流自动关闭.在此之后,任何一个对当前页面进行操作的document.write()方法将打开—个新的输出流,它将清除当前页面内容. 必须确保调用document.close() ...

  9. pgAgent设定定时备份

    PostgreSQL定时自动备份 简介 PostgreSQL数据库中未提供数据库的定时备份功能,所以需要结合备份和定时job功能来共同实现. 这里我选取了2种定时job方式,crontab是Linux ...

  10. YAMLException: can not read a block mapping entry; a multiline key may not be an implicit key at line 5, column 1:

    创建的md文件头部声明中没有加空格.