spring事物的传播行为及隔离
关于@Transactional注解: 添加事务注解 个人疑问有一些,结尾来说,用教程例子来说吧。 我的代码如下: 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注解确实满足原子性操作,要么都做,要么不做 我个人觉得因为在更新账户余额,那有个判断先查询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'); ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |