事物注解:@Transactional
事物举例:
sql:
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`username` varchar(255) NOT NULL,
`balance` int(11) DEFAULT NULL,
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('Tom', '100');
-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`isbn` varchar(255) NOT NULL,
`book_name` varchar(255) DEFAULT NULL,
`price` int(11) DEFAULT NULL,
PRIMARY KEY (`isbn`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES ('0001', 'Java', '50');
-- ----------------------------
-- Table structure for book_stock
-- ----------------------------
DROP TABLE IF EXISTS `book_stock`;
CREATE TABLE `book_stock` (
`isbn` varchar(255) NOT NULL,
`stock` int(11) DEFAULT NULL,
PRIMARY KEY (`isbn`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- ----------------------------
-- Records of book_stock
-- ----------------------------
INSERT INTO `book_stock` VALUES ('0001', '10');
INSERT INTO `book_stock` VALUES ('0002', '10');
(1)引入依赖
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework</groupId> 4 <artifactId>spring-webmvc</artifactId> 5 <version>5.2.9.RELEASE</version> 6 </dependency> 7 <dependency> 8 <groupId>mysql</groupId> 9 <artifactId>mysql-connector-java</artifactId> 10 <version>8.0.25</version> 11 </dependency> 12 <!--切面依赖--> 13 <dependency> 14 <groupId>org.springframework</groupId> 15 <artifactId>spring-aspects</artifactId> 16 <version>5.2.9.RELEASE</version> 17 </dependency> 18 19 <!--jdbc依赖--> 20 <dependency> 21 <groupId>org.springframework</groupId> 22 <artifactId>spring-jdbc</artifactId> 23 <version>5.2.9.RELEASE</version> 24 </dependency> 25 26 <dependency> 27 <groupId>org.mybatis</groupId> 28 <artifactId>mybatis-spring</artifactId> 29 <version>2.0.6</version> 30 </dependency> 31 <dependency> 32 <groupId>org.mybatis</groupId> 33 <artifactId>mybatis</artifactId> 34 <version>3.5.7</version> 35 </dependency> 36 37 <dependency> 38 <groupId>com.alibaba</groupId> 39 <artifactId>druid</artifactId> 40 <version>1.2.8</version> 41 </dependency> 42 43 44 45 </dependencies>
(2)spring配置文件
<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫包--> <context:component-scan base-package="com.qy143.service"/> <!-- 配置jdbc--> <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/aoptransaction?serverTimezone=Asia/Shanghai"/> <property name="username" value="root"/> <property name="password" value="123@qwe"/> <!-- 最大连接数量,最小连接数量,等待时间--> <property name="maxActive" value="10"/> <property name="minIdle" value="3"/> <!-- 初始化连接数--> <property name="initialSize" value="5"/> <!-- 单位是毫秒--> <property name="maxWait" value="5000"/> </bean> <!-- 把mybatis配置文件中的内容整合到spring中--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource"/> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 为指定包下的dao方法生成实现类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.qy143.dao"/> </bean> <!-- 1.事物管理 理解为事物切面 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="datasource"/> </bean> <!-- 2.开启事物注解 transaction-manager:可以省略 但是前提是你的事物管理的id必须是transactionManager(事物管理器) http://www.springframework.org/schema/tx --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
(3)dao接口
public interface BookShopDao { /** * 根据图书编号查询图书价格 * @param isbn * @return */ public int findBookPriceByIsbn(String isbn); /** * 根据书得编号修改书得库存 * @param isbn */ public int updateBookStockByIsbn(String isbn); /** * 修改账号余额 * @param username * @param money */ public void updateAccount(@Param("username") String username,@Param("money") int money); /** * 查询库存 * @param isbn * @return */ int findBookStockByIsbn(String isbn); /** * 根据账号查询余额 * @param username * @return */ int findAccountBalanceByUsername(String username); }
(4)dao得映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.qy143.dao.BookShopDao"> <!-- 根据书得编号修改书得库存--> <update id="updateBookStockByIsbn"> update book_stock set stock=stock-1 where isbn=#{isbn} </update> <!-- 修改账号余额--> <update id="updateAccount"> update account set balance=balance-#{money} where username=#{username} </update> <!--根据图书编号查询图书价格--> <select id="findBookPriceByIsbn" resultType="java.lang.Integer"> select price from book where isbn=#{isbn} </select> <!-- 查询库存--> <select id="findBookStockByIsbn" resultType="java.lang.Integer"> select stock from book_stock where isbn=#{isbn} </select> <!-- 根据账号查询余额--> <select id="findAccountBalanceByUsername" resultType="java.lang.Integer"> select balance from Account where username=#{username} </select> </mapper>
(5) service层得接口
public interface BookShopService { /** * 购买 * @param isbn * @param username */ public void purchase(String isbn,String username); }
(6)Service实现类
@Service("bookShopServiec") public class BookShopServiceImpl implements BookShopService { @Autowired private BookShopDao bookShopDao; //rollbackFor:针对那种异常才会回滚. //noRollbackFor:哪些异常不回滚 //readOnly:只读 针对查询功能 findById(); //timeout:设置事物超时时间。单位为妙 @Transactional(propagation = Propagation.REQUIRED,rollbackFor = SQLException.class) public void purchase(String isbn, String username) { // 业务代码 // 1.根据书的编号查询书的价格 int price = bookShopDao.findBookPriceByIsbn(isbn); // 2.查询指定书的库存 int stock = bookShopDao.findBookStockByIsbn(isbn); if (stock>0){ //修改库存数量 bookShopDao.updateBookStockByIsbn(isbn); }else { throw new RuntimeException("编号为"+isbn+"的库存不足"); } // 3.查询指定用户的余额 int balance = bookShopDao.findAccountBalanceByUsername(username); if (balance>=price){ //扣款 bookShopDao.updateAccount(username,price); }else{ throw new RuntimeException("账号为"+username+"的余额不足"); } } }
(7)测试类
public class Test { public static void main(String[] args) { ApplicationContext app =new ClassPathXmlApplicationContext("spring.xml"); BookShopService bookShopServiec = (BookShopService)app.getBean("bookShopServiec"); bookShopServiec.purchase("0001","Tom"); } }