关于@Transactional注解:
添加事务注解
1.使用 propagation 指定事务的传播行为,即当前的事务方法被另外一个事务方法调用时
如何使用事务,默认取值为 required,即使用调用方法的事务
REQUIRES_NEW: 事务自己的事务,调用的事务方法的事务被挂起.
2.使用 isolation 指定事务的隔离级别,最常用的取值为 READ_COMMITTED
3.默认情况下 Spring 的声明式事务对所有的运行时异常进行回滚. 也可以通过对应的
属性进行设置. 通常情况下去默认值即可.
4.使用 readOnly 指定事务是否为只读. 表示这个事务只读取数据但不更新数据,
这样可以帮助数据库引擎优化事务. 若真的事一个只读取数据库值的方法,应设置 readOnly=true
5.使用 timeout 指定强制回滚之前事务可以占用的时间。
个人疑问有一些,结尾来说,用教程例子来说吧。
我的代码如下:
BookShopDao接口
package com.demo.spring.bean; public interface BookShopDao { // 根据书的编号返回书的单价 int findBookPriceByIsbn(String isbn); 根据书的编号返回输的库存 void updateBookStock(String isbn); 更新用户账户余额 void updateUserAccount(String username, price); }
实现类
import org.springframework.beans.factory.annotation.Autowired; org.springframework.jdbc.core.JdbcTemplate; org.springframework.stereotype.Repository; @Repository("bookShopDao") class BookShopDaoImpl implements BookShopDao { @Autowired private JdbcTemplate jdbcTemplate; @Override findBookPriceByIsbn(String isbn) { TODO Auto-generated method stub String sql = "SELECT price FROM book WHERE isbn=?"; Integer price = jdbcTemplate.queryForObject(sql,Integer.class,isbn); return price; } @Override updateBookStock(String isbn) { TODO Auto-generated method stub String sql = "SELECT stock FROM book_stock WHERE isbn= ? "; Integer stock = jdbcTemplate.queryForObject(sql,1)">if (stock == 0) { throw new BookStockException("库存不足!!"); } String sql1 = "UPDATE book_stock SET stock=stock-1 WHERE isbn=?"; jdbcTemplate.update(sql1,isbn); } @Override price) { TODO Auto-generated method stub String sql1 = "SELECT balance FROM account WHERE username= ? "; Integer account = jdbcTemplate.queryForObject(sql1,username); if (account < price) { new AccountException("余额不足!!"); } String sql = "UPDATE account SET balance=balance-? WHERE username=?"; jdbcTemplate.update(sql,price,username); } }
BookShopService接口
BookShopService { 购书 purchase(String username,String isbn); }
实现类
org.springframework.stereotype.Service; org.springframework.transaction.annotation.Transactional; @Service("bookShopService"class BookShopServiceImpl BookShopService { @Autowired BookShopDao bookShopDao; @Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED,readOnly=true,timeout=5,noRollbackFor=AccountException.class) @Transactional @Override try { Thread.sleep(5000); } catch (InterruptedException e) { TODO Auto-generated catch block e.printStackTrace(); } TODO Auto-generated method stub int price = bookShopDao.findBookPriceByIsbn(isbn); bookShopDao.updateBookStock(isbn); bookShopDao.updateUserAccount(username,price); } }
Cashier批量购书接口
java.util.List; Cashier { 批量购书 void checkout(String username,List<String> isbns); }
实现类
org.springframework.stereotype.Service; @Service("cashier"class CashierImpl Cashier { @Autowired BookShopService bookShopService; @Transactional @Override isbns) { for (String isbn : isbns) { bookShopService.purchase(username,isbn); } } }
账户余额不足及库存不足异常(自定义异常)
class AccountException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public AccountException() { super(); TODO Auto-generated constructor stub } AccountException(String message,Throwable cause,boolean enableSuppression,1)">boolean writableStackTrace) { (message,cause,enableSuppression,writableStackTrace); AccountException(String message) { (message); AccountException(Throwable cause) { (cause); } }
class BookStockException BookStockException() { BookStockException(String message,1)"> BookStockException(String message) { BookStockException(Throwable cause) { } }
测试类
java.util.Arrays; org.junit.Test; org.springframework.context.ApplicationContext; org.springframework.context.support.ClassPathXmlApplicationContext; MainTest { ApplicationContext ctx; @Autowired Cashier cashier; { ctx=new ClassPathXmlApplicationContext("bean.xml"); cashier=(Cashier) ctx.getBean("cashier"); } @Test test(){ System.out.println(bookShopDao.findBookPriceByIsbn("1001")); cashier.checkout("rongrong",Arrays.asList("1001","1002")); } }
bean文件
<?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:aop="http://www.springframework.org/schema/aop" 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-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <!-- 装载自导导入的包 --> context:component-scan base-package="com.demo.spring.bean"></context:component-scan 引入外部数据源 context:property-placeholder location="classpath:db.properties"/> 配置MysqL数据源 bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> property name="driverClassName" value="${db.driverClassName}"property="url"="${db.url}"="username"="${db.username}"="password"="${db.password}"</bean 配置jdbc模板 ="jdbcTemplate"="org.springframework.jdbc.core.JdbcTemplate"="dataSource" ref="datasource" 配置事务管理器 ="transactionManagertest"="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 启用事务注解 tx:annotation-driven transaction-manager="transactionManagertest"/> beans>
数据源
db.driverClassName=com.MysqL.jdbc.Driver db.url=jdbc:MysqL:localhost:3306/spring db.username=root db.password=root
疑问如下:
前提条件:用户按照1001,1002这种顺序去购书,调用checkout接口批量购书
@Transactional注解确实满足原子性操作,要么都做,要么不做
但是,我试验了下,如果在public void checkout(String username,List<String> isbns) 上方不加Transactional
与在public void purchase(String username,String isbn)上方加@Transactional(propagation=Propagation.REQUIRES_NEW效果一样
当账户余额为120,可以满足账户减去1001的单价,1001的库存减1
但是,将账户余额改为80,从单价上看可以买1002那本书,按照上面的顺序去买书
按照上面加上注解@Transactional(propagation=Propagation.REQUIRES_NEW效果一样,根本不好使,
我个人觉得因为在更新账户余额,那有个判断先查询1001的书的单价确实大于当前账户余额80,先判断了,所以抛异常后面代码就不走了
另外当前账户余额可以买1002这本书,想在不改变购书的顺序情况下,用@Transactional注解实现,可以买1002这本书?,减去当前账户余额80,更新1002书的库存,哪位大神看到,帮我看下,怎么用这个注解实现?
附上:sql
/* Navicat MysqL Data Transfer Source Server : myTestdata Source Server Version : 50627 Source Host : localhost:3306 Source Database : spring Target Server Type : MysqL Target Server Version : 50627 File Encoding : 65001 Date: 2017-01-18 11:28:50 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure account -- ---------------------------- DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `username` varchar(50) NOT NULL,`balance` int(11) DEFAULT NULL,PRIMARY KEY (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=gbk; -- ---------------------------- -- Records of account -- ---------------------------- INSERT INTO `account` VALUES ('rongrong','300'); INSERT INTO `account` VALUES ('zhangsan','200'); -- ---------------------------- -- Table structure book -- ---------------------------- DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `isbn` varchar(50 Records of book -- ---------------------------- INSERT INTO `book` VALUES ('1001','java','100'); INSERT INTO `book` VALUES ('1002','python','60' book_stock -- ---------------------------- DROP TABLE IF EXISTS `book_stock`; CREATE TABLE `book_stock` ( `isbn` varchar(50 Records of book_stock -- ---------------------------- INSERT INTO `book_stock` VALUES ('1001','10'); INSERT INTO `book_stock` VALUES ('1002','10');