Demand:
Users purchase books, purchase success, inventory updates, account balance updates, if the balance or inventory is not enough, can not buy success, resulting in abnormal
Data sheet:
Account: List of accounts (including user name and balance)
Book: Books table (ID, title, book price)
Book_stock: Inventory table (ID, book inventory)
Code implementation:
1. Interface for book purchase
package com.atguigu.spring.tx;public interface BookShopDao { //根据书号获取书的单价 public int findBookPriceByIsbn(String isbn); //更新书的库存, 使书号对应的库存 - 1 public void updateBookStock(String isbn); //更新用户的账户余额: 使 username 的 balance - price public void updateUserAccount(String username, int price);}
Package Com.atguigu.spring.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 Updatebookstock (string ISBN) {//Check the inventory is sufficient, if not enough, throws an exception String sql2 = "Select Stock from Book_stock where ISBN =? "; int stock = Jdbctemplate.queryforobject (Sql2, Integer.class, ISBN); if (stock = = 0) {throw new bookstockexception ("Insufficient stock! "); } String sql = "Update book_stock set stock = stock-1 where ISBN =?"; Jdbctemplate.update (sql, ISBN); } @Override public void UPDATEUSERACCOunt (string username, int price) {//verifies that the balance is sufficient, if insufficient, throws an exception String sql2 = "Select balance from account where u Sername =? "; int balance = Jdbctemplate.queryforobject (SQL2, Integer.class, username); if (balance < price) {throw new useraccountexception ("Insufficient balance!"); } String sql = "Update account set balance = Balance-?" where username =? "; Jdbctemplate.update (SQL, price, username); }}
package com.atguigu.spring.tx;public interface BookShopService { public void purchase(String username, String isbn);}
package com.atguigu.spring.tx;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Service("bookShopService")public class BookShopServiceImpl implements BookShopService { @Autowired private BookShopDao bookShopDao; //添加事务注解 @Transactional @Override public void purchase(String username, String isbn) { //1. 获取书的单价 int price = bookShopDao.findBookPriceByIsbn(isbn); //2. 更新书的库存 bookShopDao.updateBookStock(isbn); //3. 更新用户余额 bookShopDao.updateUserAccount(username, price); }}
2. Test method
Package Com.atguigu.spring.tx;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Springtransactiontest {private ApplicationContext CTX = null; Private Bookshopdao Bookshopdao = null; Private Bookshopservice bookshopservice = null; {CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); Bookshopdao = Ctx.getbean (Bookshopdao.class); Bookshopservice = Ctx.getbean (Bookshopservice.class); } @Test public void Testbookshopservice () {bookshopservice.purchase ("AA", "1001"); } @Test public void Testbookshopdaoupdateuseraccount () {Bookshopdao.updateuseraccount ("AA", 100); } @Test public void Testbookshopdaoupdatebookstock () {Bookshopdao.updatebookstock ("1001"); } @Test public void Testbookshopdaofindpricebyisbn () {System.out.println (BOOKSHOPDAO.FINDBOOKPRICEBYISBN ("10 01 ")); }}
3. Error throws exception
package com.atguigu.spring.tx;public class BookStockException extends RuntimeException{ /** * */ private static final long serialVersionUID = 1L; 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.atguigu.spring.tx;public class Useraccountexception extends runtimeexception{/** * */ Private static final long serialversionuid = 1L; Public Useraccountexception () {super (); TODO auto-generated Constructor stub} public useraccountexception (String message, Throwable cause, Boolean enabl Esuppression, Boolean writablestacktrace) {super (message, cause, enablesuppression, writablestacktrace) ; TODO auto-generated Constructor stub} public useraccountexception (String message, throwable cause) {Supe R (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}}
<?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.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX Http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <context:component-scan base-package=" Com.atguigu.spring "></context:component-scan> <!--import resource Files--<context:property-placeholder Locat ion= "Classpath:db.properties"/> <!--configuration c3p0 database--<bean id= "DataSource" class= "com.mchange.v2. C3p0. Combopooleddatasource "> <property name=" User "ValuE= "${jdbc.user}" ></property> <property name= "password" value= "${jdbc.password}" ></property> <property name= "Jdbcurl" value= "${jdbc.jdbcurl}" ></property> <property name= "Driverclass" value = "${jdbc.driverclass}" ></property> <property name= "initialpoolsize" value= "${jdbc.initpoolsize}" >& lt;/property> <property name= "maxpoolsize" value= "${jdbc.maxpoolsize}" ></property> </bean> <!--configuring Spring JdbcTemplate--<bean id= "JdbcTemplate" class= "Org.springframework.jdbc.core.Jdbc Template "> <property name=" dataSource "ref=" DataSource "></property> </bean> <!--configuration transactions Manager--<bean id= "TransactionManager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionMan Ager "> <property name=" dataSource "ref=" DataSource "></property> </bean> <!--enable transaction--& Gt <tx:annotation-dRiven transaction-manager= "TransactionManager"/></beans>
Spring Learning-DAY13