shop--6.店铺注册--service层实现(事务)
事物的回滚
1.插入店铺信息-》2.返回店铺Id-》3.根据店铺Id创建存储图片的文件夹-》4.把文件夹的地址更新回店铺信息中
在实现service接口中添加@Transational事务标签
只有当程序抛出RuntimeException的异常或继承RuntimeException类 时,事务才会回滚,如果只是抛出Exception,事物不会回滚
@Service public class ShopServiceImpl implements ShopService { @Autowired private ShopDao shopDao; @Override @Transactional //1.插入店铺信息-》2.返回店铺Id-》3.根据店铺Id创建存储图片的文件夹-》4.把文件夹的地址更新回店铺信息中 public ShopExecution addShop(Shop shop, CommonsMultipartFile shopImg) { //空值判定 if(shop == null){ return new ShopExecution( ShopStateEnum.NULL_SHOP); } try{ //给店铺信息赋初始值 //初识店铺都是 0 审核中 shop.setStatus(0); shop.setCreateTime( new Date() ); shop.setLastEditTime( new Date() ); int effectedNum = shopDao.insertShop( shop ); //判断插入店铺是否成功,若不成功,则回滚事务 if(effectedNum <= 0){ throw new ShopOperationException("插入店铺信息失败"); } else{ //存储图片 if(shopImg != null){ try{ addShopImg(shop, shopImg); }catch(Exception e){ throw new ShopOperationException( "addShopImg error" + e.getMessage()); } effectedNum = shopDao.updateShop( shop ); if(effectedNum <= 0){ throw new ShopOperationException("更新图片地址失败"); } } } }catch (Exception e){ throw new ShopOperationException("addShop error: " + e.getMessage()); } return new ShopExecution(ShopStateEnum.CHECK, shop); } /** * 将店铺图片添加到用户相对的文件夹下,并且将店铺信息中店铺图片的地址更新 * @param shop * @param shopImg */ private void addShopImg(Shop shop, CommonsMultipartFile shopImg) { String relativeImgPath = PathUtil.getShopImgPath(shop.getShopId()); String realRelativeImgPath = ImageUtil.generateThumbnail( shopImg, relativeImgPath ); shop.setShopImg(realRelativeImgPath); } }
抛出的RuntimeException可以自己定义一个异常类ShopOperationException,继承RuntimeException,这样看上去更加直观的知道是什么异常
public class ShopOperationException extends RuntimeException { public ShopOperationException(String msg){ super(msg); } }