Spring入门初体验(3)----声明式事务(基于注解)
来源:互联网 发布:罗京艾滋病真假 知乎 编辑:程序博客网 时间:2024/04/29 02:40
1.首先来建立需要的数据库表
-- ------------------------------ Table structure for `account`-- ----------------------------DROP TABLE IF EXISTS `account`;CREATE TABLE `account` ( `username` varchar(45) NOT NULL DEFAULT '', `balance` int(160) DEFAULT NULL, PRIMARY KEY (`username`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of account-- ----------------------------INSERT INTO `account` VALUES ('AA', '40');-- ------------------------------ Table structure for `book`-- ----------------------------DROP TABLE IF EXISTS `book`;CREATE TABLE `book` ( `isbn` int(11) NOT NULL DEFAULT '0', `book_name` varchar(45) DEFAULT NULL, `price` int(11) DEFAULT NULL, PRIMARY KEY (`isbn`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of book-- ----------------------------INSERT INTO `book` VALUES ('1001', 'java', '60');INSERT INTO `book` VALUES ('1002', 'oracle', '70');-- ------------------------------ Table structure for `book_stock`-- ----------------------------DROP TABLE IF EXISTS `book_stock`;CREATE TABLE `book_stock` ( `isbn` varchar(45) NOT NULL DEFAULT '', `stock` int(11) DEFAULT NULL, PRIMARY KEY (`isbn`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of book_stock-- ----------------------------INSERT INTO `book_stock` VALUES ('1001', '1');INSERT INTO `book_stock` VALUES ('1002', '8');-- ------------------------------ Table structure for `departments`-- ----------------------------DROP TABLE IF EXISTS `departments`;CREATE TABLE `departments` ( `ID` int(11) NOT NULL DEFAULT '0', `DEPT_NAME` varchar(45) DEFAULT NULL, PRIMARY KEY (`ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of departments-- ----------------------------INSERT INTO `departments` VALUES ('1', '财务部');INSERT INTO `departments` VALUES ('2', '开发部');INSERT INTO `departments` VALUES ('3', '人事部');INSERT INTO `departments` VALUES ('4', '公关部');-- ------------------------------ Table structure for `employees`-- ----------------------------DROP TABLE IF EXISTS `employees`;CREATE TABLE `employees` ( `ID` int(11) NOT NULL DEFAULT '0', `LAST_NAME` varchar(25) DEFAULT NULL, `EMAIL` varchar(25) DEFAULT NULL, `DEPT_ID` int(11) DEFAULT NULL, PRIMARY KEY (`ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of employees-- ----------------------------INSERT INTO `employees` VALUES ('0', 'AA', 'aa@@@tain.com', '1');INSERT INTO `employees` VALUES ('1', 'Tom', '123@qq.com', '1');INSERT INTO `employees` VALUES ('2', 'tian', '323@qq.com', '2');INSERT INTO `employees` VALUES ('3', 'Jerry', 'ff@qq.com', '3');INSERT INTO `employees` VALUES ('4', 'Rose', 'aa@164.com', '3');INSERT INTO `employees` VALUES ('5', 'tianjun', 'cc@sina.com', '2');INSERT INTO `employees` VALUES ('6', 'AA', 'aa@@@tain.com', '1');INSERT INTO `employees` VALUES ('7', 'BB', 'bb@@@tain.com', '2');INSERT INTO `employees` VALUES ('8', 'CC', 'cc@@@tain.com', '3');INSERT INTO `employees` VALUES ('9', 'DD', 'dd@@@tain.com', '4');INSERT INTO `employees` VALUES ('10', 'EE', 'ee@@@tain.com', '5');INSERT INTO `employees` VALUES ('11', 'FF', '123@qq.com', '2');配置spring的xml文件如下:主要是配置事务管理器和启动事务管理器。
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"><!-- 导入文件资源 --><!-- <context:property-placeholder location="classpath:db.properties"/> --><context:component-scan base-package="com.tian.tx"></context:component-scan><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property><property name="url"><value>jdbc:mysql://localhost:3306/spring4</value></property><property name="username"><value>root</value></property><property name="password"><value>123</value></property></bean><!-- 配置JDBCTemplate --><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><!-- 配置 事务管理器 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 启用事务注解 --><tx:annotation-driven transaction-manager="transactionManager"/></beans>Dao基类和继承类
package com.tian.tx;public interface BookShopDao {public int findBookPriceByISBN(String ISBN);//跟新数的库存,是书号对应的库存减一public void updateBookStack(String isbn);//跟新用户的账户余额:username的(balance-price)public void updateUserAccount(String username,int price);}
package com.tian.tx;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository;@Repository("bookShopDao")public class BookShopDaoImpl implements BookShopDao {@Autowiredprivate JdbcTemplate jdbcTemplate;@Overridepublic int findBookPriceByISBN(String ISBN) {String sql = "select price from book where isbn=?";return jdbcTemplate.queryForObject(sql, Integer.class, ISBN);}@Overridepublic void updateBookStack(String isbn) {String sql2="select stock from book_stock where isbn=?";int stock = jdbcTemplate.queryForObject(sql2, Integer.class, isbn);if(stock<0){throw new BookStockException("库存不足!");}String sql = "update book_stock set stock = stock-1 where isbn = ?";jdbcTemplate.update(sql, isbn);}@Overridepublic void updateUserAccount(String username, int price) {// TODO Auto-generated method stubString sql2="select balance from account where username=?";int balance = jdbcTemplate.queryForObject(sql2, Integer.class, username);if(balance < price){throw new UserAccountException("余额不足!");}String sql = "update account set balance = balance -? where username= ?";jdbcTemplate.update(sql,price,username);}}
最后就是来是来实现业务逻辑的service类
package com.tian.tx;public interface BookShopService {public void purchase(String username,String isbn);}
package com.tian.tx;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;@Service("bookShopService")public class BookShopServiceImpl implements BookShopService {@Autowiredprivate BookShopDao bookShopDao;@Transactionalpublic void purchase(String username, String isbn) {int price = bookShopDao.findBookPriceByISBN(isbn);bookShopDao.updateBookStack(isbn);bookShopDao.updateUserAccount(username, price);}}补充:两个自定义的抛出异常的类:
package com.tian.tx;public class BookStockException extends RuntimeException {public BookStockException() {super();// TODO Auto-generated constructor stub}public BookStockException(String message, Throwable cause,boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);// TODO Auto-generated constructor stub}public BookStockException(String message, Throwable cause) {super(message, cause);// TODO Auto-generated constructor stub}public BookStockException(String message) {super(message);// TODO Auto-generated constructor stub}public BookStockException(Throwable cause) {super(cause);// TODO Auto-generated constructor stub}}
package com.tian.tx;public class UserAccountException extends RuntimeException {public UserAccountException() {super();// TODO Auto-generated constructor stub}public UserAccountException(String message, Throwable cause,boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);// TODO Auto-generated constructor stub}public UserAccountException(String message, Throwable cause) {super(message, cause);// TODO Auto-generated constructor stub}public UserAccountException(String message) {super(message);// TODO Auto-generated constructor stub}public UserAccountException(Throwable cause) {super(cause);// TODO Auto-generated constructor stub}}
最后就是测试:
private ApplicationContext ctx =null;private BookShopDao bookDao = null;private BookShopService bs =null;{ctx = new ClassPathXmlApplicationContext("applicationContext.xml");bookDao = ctx.getBean(BookShopDao.class);bs = ctx.getBean(BookShopService.class);}@Testpublic void test4(){bs.purchase("AA", "1001");}
大家可以上试下如果没有注解@Transaction,执行的结果是,余额会抛出异常,但是库存stock依然会减一,就是东西没卖,库存变了,不合理;加了事务注解后,就会自动回滚了,余额异常,库存不变,符合常识。
0 0
- Spring入门初体验(3)----声明式事务(基于注解)
- Spring(四)基于注解配置IOC容器&基于注解实现声明式事务
- Spring(四)基于注解配置IOC容器&基于注解实现声明式事务
- Spring 基于注解方式声明式事务
- spring声明式事务管理(基于注解)
- spring中jdbc声明式事务和spring基于xmlschema、annotation的声明式事务(事务3)
- Spring声明式事务(Annotation注解方式)
- Spring入门学习初体验(2)----基于注解的AOP
- Spring声明式事务管理(基于注解方式实现)
- Spring注解声明式事务配置
- spring配置声明式事务--注解方式
- Spring配置声明式事务--注解方式
- Spring声明式事务注解@Transactional
- Spring学习-34:Spring中的事务管理之声明式事务(基于注解)
- [spring,mysql] spring使用注解式事务声明(@Transactional)无法回滚
- Spring4学习笔记-声明式事务(基于注解的方式)
- Spring中事务(基于xml && 基于注解)
- spring事务配置,声明式事务管理和基于@Transactional注解的使用
- CSS从大图中抠取小图完整教程(background-position应用)
- 介绍几个.NET开发中好的开发习惯
- HDU 4956/BC 5A Poor Hanamichi
- 设计模式之相关原则
- 安装ubuntu并切换到Gnome经典桌面
- Spring入门初体验(3)----声明式事务(基于注解)
- Java运算符优先级
- 牛腩新闻发布系统(二)
- 欧拉函数详解 + 整数唯一分解定理 + 欧拉定理(高阶幂次取模)
- Android官方命令深入分析之Hierarchy Viewer
- ios 微信支付页面跳转问题
- hdu 1151 - > 双向路径搜索解决覆盖问题
- 【bzoj1018】【SHOI2008】【堵塞的交通traffic】
- hdu 1151 - > 双向路径搜索解决覆盖问题