1.在springBoot项目中service的实现类可以通过注解@Transactional添加事务
注意:必须是public方法 , 默认捕捉运行时异常
1.1 如果在Service层用了try catch,在catch里面再抛出一个 RuntimeException异常,这样出了异常才会回滚
1.2你还可以直接在catch后面写一句回滚代码(TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();)来实现回滚,这样的话,就可以在抛异常后也能return 返回值;比较适合需要拿到Service层的返回值的场景。
2.可以通过设置包名统一设置事务
3.自定义代码内设置事务
(1).注入事务管理类
@Resource
PlatformTransactionManager platformTransactionManager;
@Resource
TransactionDefinition transactionDefinition;
2)使用事务
@Resource
private OrderMapper orderMapper;
@Resource
private OrderItemMapper orderItemMapper;
@Resource
private ProductMapper productMapper;
//购买商品id
private int purchaseProductId = 100100;
//购买商品数量
private int purchaseProductNum = 1;
@Autowired
private PlatformTransactionManager platformTransactionManager;
@Autowired
private TransactionDefinition transactionDefinition;
private Lock lock = new ReentrantLock();
// @Transactional(rollbackFor = Exception.class)
public Integer createOrder() throws Exception
{
Product product = null;
lock.lock();
try
{
TransactionStatus transaction1 = platformTransactionManager.getTransaction(transactionDefinition);
product = productMapper.selectByPrimaryKey(purchaseProductId);
if(product == null)
{
platformTransactionManager.rollback(transaction1);
throw new Exception("购买商品:" + purchaseProductId + "不存在");
}
//商品当前库存
Integer currentCount = product.getCount();
System.out.println(Thread.currentThread().getName() + "库存数:" + currentCount);
//校验库存
if(purchaseProductNum > currentCount)
{
platformTransactionManager.rollback(transaction1);
throw
new Exception("商品" + purchaseProductId + "仅剩" + currentCount + "件,无法购买");
}
productMapper.updateProductCount(purchaseProductNum, "xxx", new Date(), product.getId());
platformTransactionManager.commit(transaction1);
}
finally
{
lock.unlock();
}
TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
Order order = new Order();
order.setOrderAmount(product.getPrice().multiply(new BigDecimal(purchaseProductNum)));
order.setOrderStatus(1);//待处理
order.setReceiverName("xxx");
order.setReceiverMobile("13311112222");
order.setCreateTime(new Date());
order.setCreateUser("xxx");
order.setUpdateTime(new Date());
order.setUpdateUser("xxx");
orderMapper.insertSelective(order);
OrderItem orderItem = new OrderItem();
orderItem.setOrderId(order.getId());
orderItem.setProductId(product.getId());
orderItem.setPurchasePrice(product.getPrice());
orderItem.setPurchaseNum(purchaseProductNum);
orderItem.setCreateUser("xxx");
orderItem.setCreateTime(new Date());
orderItem.setUpdateTime(new Date());
orderItem.setUpdateUser("xxx");
orderItemMapper.insertSelective(orderItem);
platformTransactionManager.commit(transaction);
return order.getId();
}