shop--6.店铺注册--店铺注册之Service层的实现

Service的流程

1.插入店铺信息->2.返回店铺Id->3.根据店铺Id创建存储图片的文件夹->4.把文件夹的地址更新回店铺信息中

只要有一步出错 就要事务回滚

创建ShopService 接口

接着写实现类ShopServiceImpl

在实现service接口中添加@Transational事务标签

只有当程序抛出RuntimeException的异常或继承RuntimeException类 时,事务才会回滚,如果只是抛出Exception,事物不会回滚

 1 @Service
 2 public class ShopServiceImpl implements ShopService {
 3  
 4     @Autowired
 5     private ShopDao shopDao;
 6  
 7     @Override
 8     @Transactional
 9     //1.插入店铺信息->2.返回店铺Id->3.根据店铺Id创建存储图片的文件夹->4.把文件夹的地址更新回店铺信息中
10     public ShopExecution addShop(Shop shop, CommonsMultipartFile shopImg) {
11         //空值判定
12         if(shop == null){
13             return new ShopExecution( ShopStateEnum.NULL_SHOP);
14         }
15         try{
16             //给店铺信息赋初始值
17             //初识店铺都是 0 审核中
18             shop.setStatus(0);
19             shop.setCreateTime( new Date() );
20             shop.setLastEditTime( new Date() );
21  
22             int effectedNum = shopDao.insertShop( shop );
23             //判断插入店铺是否成功,若不成功,则回滚事务
24             if(effectedNum <= 0){
25                 throw new ShopOperationException("插入店铺信息失败");
26             } else{
27                 //存储图片
28                 if(shopImg != null){
29                     try{
30                         addShopImg(shop, shopImg);
31                     }catch(Exception e){
32                         //需要终止事务的进行 就用RuntimeExeception
33                         throw new ShopOperationException( "addShopImg error" + e.getMessage());
34                     }
35                     //更新店铺的图片地址 因为上面只创建了createtime lasttime shopid
36                     effectedNum = shopDao.updateShop( shop );
37                     if(effectedNum <= 0){
38                         throw new ShopOperationException("更新图片地址失败");
39                     }
40                 }
41             }
42         }catch (Exception e){
43             throw new ShopOperationException("addShop error: " + e.getMessage());
44         }
45         return new ShopExecution(ShopStateEnum.CHECK, shop);
46     }
47     /**
48      * 将店铺图片添加到用户相对的文件夹下,并且将店铺信息中店铺图片的地址更新
49      * @param shop
50      * @param shopImg
51      */
52     private void addShopImg(Shop shop, CommonsMultipartFile shopImg) {
53         //获取shop图片目录的相对值路径
54         String relativeImgPath = PathUtil.getShopImgPath(shop.getShopId());
55         String realRelativeImgPath = ImageUtil.generateThumbnail( shopImg, relativeImgPath );
56         shop.setShopImg(realRelativeImgPath);
57     }
58 }

 

抛出的RuntimeException可以自己定义一个异常类ShopOperationException,继承RuntimeException,这样看上去更加直观的知道是什么异常

1 public class ShopOperationException extends RuntimeException {
2     public ShopOperationException(String msg){
3         super(msg);
4     }
5 }

 

转载于:https://www.cnblogs.com/windbag7/p/9346257.html

你可能感兴趣的:(shop--6.店铺注册--店铺注册之Service层的实现)