@ServicepublicclassStockServiceImplimplementsIStockService{@AutowiredprivateStockMapper stockMapper;@AutowiredprivateTransactionTemplate transactionTemplate;@OverridepublicvoidupdateStock(String productName,int quantity){
transactionTemplate.execute(status ->{StockDO stock = stockMapper.findStockByProductName(productName);if(stock ==null|| stock.getQuantity()< quantity){thrownewRuntimeException("Not enough stock for "+ productName);}// 在事务中执行悲观锁定和库存更新int updatedRows = stockMapper.updateStock(stock);if(updatedRows ==0){thrownewRuntimeException("The stock update was not successful for "+ productName);}returnnull;});}}
dao层
<!-- 查询库存信息并锁定 --><selectid="findStockByProductName"parameterType="String"resultMap="StockMap">
SELECT <includerefid="cols"/>
FROM <includerefid="tb_s"/>
WHERE product_name = #{productName} FOR UPDATE
</select><!-- 更新库存 --><updateid="updateStock"parameterType="com.forrest.springboot.stock.domain.StockDO">
UPDATE <includerefid="tb_s"/> SET quantity = quantity - #{quantity} WHERE id = #{id}
</update>