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.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: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 {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int findBookPriceByISBN(String ISBN) {
String sql = "select price from book where isbn=?";
return jdbcTemplate.queryForObject(sql, Integer.class, ISBN);
}
@Override
public 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);
}
@Override
public void updateUserAccount(String username, int price) {
// TODO Auto-generated method stub
String 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 {
@Autowired
private BookShopDao bookShopDao;
@Transactional
public 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);
}
@Test
public void test4(){
bs.purchase("AA", "1001");
}
大家可以上试下如果没有注解@Transaction,执行的结果是,余额会抛出异常,但是库存stock依然会减一,就是东西没卖,库存变了,不合理;加了事务注解后,就会自动回滚了,余额异常,库存不变,符合常识。