当前位置: 代码迷 >> 综合 >> Spring+Maven+jdbcTemplate+事务 实现图书买卖Demo
  详细解决方案

Spring+Maven+jdbcTemplate+事务 实现图书买卖Demo

热度:56   发布时间:2023-12-18 01:28:22.0

先来简单介绍下事务,我的理解就是 使得一系列对数据库的操作原子化。
举个栗子:

你给别人转账,你的钱少了,但是别人的账户余额没有同时增加。
或者你给别人转账,你的钱没少,别人账户余额增加了。

分析:
转账扣钱是一个操作,收账增钱又是另一个操作。
如果中途出现错误,只实现了一部分操作,那么问题可想而知。
而事务的作用就是将两个操作粘合在一起,具有原子性。
只有两个都成功,才操作成功,
只要其中一个不成功,整个操作就失败。

这里我们来实战一下,写一个小Demo:
实现图书的买卖操作,目的是 扣除用户余额,减少图书存量。
如果其中一步出错,那么终止另一个操作,使其无效。


代码我已经放到Git上,有兴趣的可以直接下载过来:

https://github.com/jjc123/Book-sale/blob/master/README.md

编写数据库:

mysql> create table book_stock(-> id int,     -> stock int     -> ); Query OK, 0 rows affected (1.18 sec)mysql> create table account(-> name varchar(11),     -> money int     -> ); Query OK, 0 rows affected (0.31 sec)mysql> create table book_price(-> id int,     -> price int     -> ); Query OK, 0 rows affected (0.43 sec)INSERT INTO account(name,money) values('小明',100);
INSERT INTO book_stock(id,stock) values(1,0);
INSERT INTO book_price(id,price) values(1,60);

配置Maven:

<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.0.8.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency></dependencies>

编写两个接口:
业务层:

public interface BookShopService {void purchase(String username,int id);
}

Dao层:

public interface BookShopDao {//根据id获取书价int findBookPriceById(int id);//根据id更新书的库存void updateBookStock(int id);//根据用户名和消费的金额更新用户余额void updateUserAccount(String name,int price);
}

实现类:

@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {
    @Autowiredprivate JdbcTemplate jdbcTemplate;/*因为不是映射一整行 所以不需要RowMapper*/@Overridepublic int findBookPriceById(int id) {String sql = "SELECT price FROM book_price WHERE id=?";return jdbcTemplate.queryForObject(sql,Integer.class,1);}@Overridepublic void updateBookStock(int id) {//验证库存是否足够,因为mysql不会帮我们验证约束String sqlStock = "SELECT stock FROM book_stock WHERE id =?";int stock =jdbcTemplate.queryForObject(sqlStock,Integer.class,id);if(stock ==0){throw new BookStockException("库存不足");}String sql ="UPDATE book_stock SET stock = stock-1 WHERE id =?";jdbcTemplate.update(sql,id);}@Overridepublic void updateUserAccount(String name, int price) {//验证账户余额String sqlAccount = "SELECT money FROM account WHERE name = ?";int money =jdbcTemplate.queryForObject(sqlAccount,Integer.class,name);if(money <price){throw new UserAccountException("余额不足");}String sql = "UPDATE account SET money = money - ? WHERE name= ?";jdbcTemplate.update(sql,price,name);}
}
@Service("bookShopService")
public class BookShopServiceImpl implements BookShopService {
    @Autowiredprivate BookShopDao bookShopDao;@Transactional@Overridepublic void purchase(String username, int id) {//获取书单价int price = bookShopDao.findBookPriceById(id);//更新书的库存bookShopDao.updateBookStock(id);//更新用户余额bookShopDao.updateUserAccount(username,price);}
}

还有两个自定义的异常类:
图书存货不足

public class BookStockException extends RuntimeException{
    public BookStockException() {}public BookStockException(String message) {super(message);}public BookStockException(String message, Throwable cause) {super(message, cause);}public BookStockException(Throwable cause) {super(cause);}public BookStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}
}

用户余额不足:

public class UserAccountException extends RuntimeException {
    public UserAccountException() {}public UserAccountException(String message) {super(message);}public UserAccountException(String message, Throwable cause) {super(message, cause);}public UserAccountException(Throwable cause) {super(cause);}public UserAccountException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}
}

配置数据源:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useAffectedRows=true&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=123456

配置xml文件:

   <!--配置book下的bean--><context:component-scan base-package="book"></context:component-scan><context:property-placeholder location="db.properties"></context:property-placeholder><bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="url" value="${jdbc.url}"></property><property name="driverClassName" value="${jdbc.driver}"></property><property name="username" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></bean><!--配置jdbcTemplate--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource="#{datasource}"></bean><!--配置事务管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource="#{datasource}"></bean><!--启动事务注解--><tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

测试类:

public class Main {private static ApplicationContext applicationContext = null;public static void main(String[] args) throws SQLException {applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");BookShopService bookShopService = (BookShopService)applicationContext.getBean("bookShopService");bookShopService.purchase("小明",1);}
}

总结:
实现通过注解将指定目录下的bean加入到ioc容器中 Bean注解都是放在实现类,但是从容器调用的时候使用的是接口类

<context:component-scan base-package="book"></context:component-scan>

如果Bean类属性中有对象的话 需要使用自动配置将其配置到Bean中,如:

@Autowiredprivate JdbcTemplate jdbcTemplate;

关于约束问题:
//验证库存是否足够,因为mysql不会帮我们验证约束,所以我们要自已来验证

        String sqlStock = "SELECT stock FROM book_stock WHERE id =?";int stock =jdbcTemplate.queryForObject(sqlStock,Integer.class,id);if(stock ==0){throw new BookStockException("库存不足");}

事务流程:

1. 置事务管理器
2. 启动事务注解
3. 在需要加事务的方法前加注解:@Transactional  
  相关解决方案