优化代码:Long userId = SecurityUtils.getUserId(); System.out.println("userId =========================== " + userId); boolean flag = permissionService.hasRole("brand"); Integer result = 0; // admin if (SecurityUtils.isAdmin(userId)) { Integer i = gsApparatusExampleMapper.selectCapacityNum(); return i; } else if (flag) { // 品牌 Long brandId = UserUtils.getBrandId(userId); List<GsShop> gsShops = gsShopMapper.selectList(Wrappers.<GsShop>lambdaQuery() .eq(GsShop::getBrandId, brandId)); List<Long> shopIds = gsShops.stream().map(gsShop -> gsShop.getId()).collect(Collectors.toList()); if (CollectionUtils.isEmpty(shopIds)) { return 0; } for (Long shopId : shopIds) { Integer i = gsApparatusExampleMapper.selectCapacity(shopId); if (i == null) { i = 0; } result += i; } return result; } // 店铺 Long shopId = UserUtils.getShopId(userId); result = gsApparatusExampleMapper.selectCapacity(shopId); if (result == null) { return 0; } return result;
时间: 2024-02-15 12:21:05 浏览: 29
可以对代码进行一些优化,主要是减少重复的数据库查询和代码块重复。
优化后的代码如下:
```java
Long userId = SecurityUtils.getUserId();
System.out.println("userId =========================== " + userId);
boolean flag = permissionService.hasRole("brand");
Integer result = 0;
// admin
if (SecurityUtils.isAdmin(userId)) {
return gsApparatusExampleMapper.selectCapacityNum();
}
if (flag) {
// 品牌
Long brandId = UserUtils.getBrandId(userId);
List<GsShop> gsShops = gsShopMapper.selectList(Wrappers.<GsShop>lambdaQuery()
.eq(GsShop::getBrandId, brandId));
List<Long> shopIds = gsShops.stream().map(GsShop::getId).collect(Collectors.toList());
result = gsApparatusExampleMapper.selectCapacityByShopIds(shopIds);
} else {
// 店铺
Long shopId = UserUtils.getShopId(userId);
result = gsApparatusExampleMapper.selectCapacity(shopId);
}
return result != null ? result : 0;
```
优化说明:
1. 将管理员权限判断提前,避免不必要的数据库查询。
2. 将品牌用户和店铺用户的逻辑合并,避免代码块重复。
3. 使用 `selectCapacityByShopIds` 方法一次性查询多个店铺的容量,减少数据库查询次数。
4. 统一处理最终结果的 null 值情况,避免重复代码。