@ApiOperation("多条件分页查询xxxx")
@GetMapping("page")
@PreAuthorize("hasAuthority('模块权限:权限:page')")
public ResponseEntity<Page<实体类>> load'xxxx'Page(Page<实体类> page,实体类 domain) {
page = 'xxxx'Service.page(page,new LambdaQueryWrapper<实体类>()
.like(条件)
.eq(条件)
.orderByDesc(条件)
);
return ResponseEntity.ok(page);
}
=================================================================================================
项目实例:
controller
:
@ApiOperation("新增xxxx")
@PostMapping
@PreAuthorize("hasAuthority('模块权限:权限:save')")
@Log(operation = "新增xxxx")
public ResponseEntity<Void> save'xxxx'(@RequestBody 实体类 domain) {
// 获取当前用户
//String userId = AuthUtil.getLoginUserId();
//domain.setUserId(Long.valueof(userId));
// 执行业务
'xxxx'Service.save(domain);
// 响应
return ResponseEntity.ok().build();
}
serviceimpl
:
@Override
@Transactional(rollbackFor = RuntimeException.class)
@CacheEvict(key = xxxConstant.xxx)
public boolean save(实体类 domain) {
// 1、补充一些信息
//1) 时间
domain.setCreateTime(new Date());
domain.setUpdateTime(new Date());
//2) 密码加密(新增用户需要)
sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
//3) 状态、版本号
domain.setStatus(1);
domain.setVersion(1);
//4) 分类层级
domain.setGrade(1);
//5) 初始数量为0
domain.setXxxCount(0L);
// 2、校验和处理
// 比如添加用户收货地址时,会判断有没有默认收获地址,没有则默认将该新增地址设置为默认收货地址
// 3、将上面补充的信息,利用mybatis新增对象
int i = 'xxxx'Mapper.insert(domain);
// 4、如果新增这个对象,在表中的属性有多表操作/
if (i > 0) {
// 比如新增一个用户,这个用户表和角色表还有一个用户角色表(3张表)
// 除了操作sys_user表外,还要操作sys_user_role表
...
}
}
return i > 0;
}
=================================================================================================
项目实例
@Override
@Transactional(rollbackFor = RuntimeException.class)
public boolean save(Prod prod) {
//新增商品对象
prod.setShopId(1L);
prod.setSoldNum(0);
prod.setVersion(0);
prod.setCreateTime(new Date());
prod.setUpdateTime(new Date());
Integer status = prod.getStatus();
if (1 == status) {
prod.setPutawayTime(new Date());
}
Prod.DeliveryModeVo deliveryModeVo = prod.getDeliveryModeVo();
prod.setDeliveryMode(JSON.toJSONString(deliveryModeVo));
int i = prodMapper.insert(prod);
if (i > 0) {
Long prodId = prod.getProdId();
//获取商品sku对象集合
List<Sku> skuList = prod.getSkuList();
//判断商品sku对象集合是否有值
if (!CollectionUtils.isEmpty(skuList) && skuList.size() != 0) {
//循环遍历商品sku对象集合
skuList.forEach(sku -> {
sku.setProdId(prodId);
sku.setActualStocks(sku.getStocks());
sku.setStocks(0);
sku.setVersion(0);
sku.setRecTime(new Date());
sku.setUpdateTime(new Date());
sku.setIsDelete(0);
});
//批量添加商品sku对象集合
skuService.saveBatch(skuList);
}
//获取商品与分组标签的关系集合
List<Long> tagIdList = prod.getTagList();
//判断是否有值
if (!CollectionUtils.isEmpty(tagIdList) && tagIdList.size() != 0) {
//循环遍历
List<ProdTagReference> prodTagReferenceList = new ArrayList<>();
tagIdList.forEach(tagId -> {
ProdTagReference prodTagReference = new ProdTagReference();
prodTagReference.setProdId(prodId);
prodTagReference.setTagId(tagId);
prodTagReference.setShopId(1L);
prodTagReference.setStatus(1);
prodTagReference.setCreateTime(new Date());
prodTagReferenceList.add(prodTagReference);
});
//批量添加商品与分组标签的关系
prodTagReferenceService.saveBatch(prodTagReferenceList);
}
}
return i>0;
}
@ApiOperation("查询xxxx详情")
@GetMapping("info/{'xxxx'Id}")
@PreAuthorize("hasAuthority('模块权限:权限:info')")
public ResponseEntity<实体类> load'xxxx'Info(@PathVariable Long roleId) {
实体类 domain = 'xxxx'Service.getById(roleId);
return ResponseEntity.ok(domain);
}
@Override
public 实体类 getById(Serializable id) {
//根据标识查询xxxx详情
实体类 domain = 'xxxx'Mapper.selectById(id);
// 多表查询
//根据id查询表1字段与表2字段关系记录list
List<表2实体类> '表2xxxx'List = '表2xxxx'Mapper.selectList(new LambdaQueryWrapper<表2实体类>()
.eq(表2实体类::getRoleId, id)
);
//判断是否有值
if (!CollectionUtils.isEmpty('表2xxxx'List) && '表2xxxx'List.size() != 0) {
//从表1字段与表2字段关系集合中获取表2字段的id集合
List<Long> '表2字段的id集合'List = '表2xxxx'List.stream()
.map(表2实体类::表2字段的id)
.collect(Collectors.toList());
表1domain.set'表2字段的id'List('表2字段的id集合'List);
}
return 表1domain;
}
=================================================================================================
@ApiOperation("修改xxxx信息")
@PutMapping
@PreAuthorize("hasAuthority('模块权限:权限:update')")
public ResponseEntity<Void> updateSysRole(@RequestBody 实体类 domain) {
'xxxx'Service.updateById(domain);
return ResponseEntity.ok().build();
}
@Override
@Transactional(rollbackFor = RuntimeException.class)
@CacheEvict(key = xxxConstant.xxx)
public boolean updateById(实体类 domain) {
// 和save操作类似
// 可能还要获取某些其绑定的一些关系,删除其原先集合
return 'xxxx'Mapper..updateById(domain)>0;
}
=================================================================================================
修改管理员信息
@Override
@Transactional(rollbackFor = RuntimeException.class)
public boolean updateById(Prod prod) {
Long prodId = prod.getProdId();
//删除商品与分组标签的关系集合
prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>()
.eq(ProdTagReference::getProdId,prodId)
);
//获取商品与分组标签的关系集合
List<Long> tagIdList = prod.getTagList();
//判断是否有值
if (!CollectionUtils.isEmpty(tagIdList) && tagIdList.size() != 0) {
//循环遍历
List<ProdTagReference> prodTagReferenceList = new ArrayList<>();
tagIdList.forEach(tagId -> {
ProdTagReference prodTagReference = new ProdTagReference();
prodTagReference.setProdId(prodId);
prodTagReference.setTagId(tagId);
prodTagReference.setShopId(1L);
prodTagReference.setStatus(1);
prodTagReference.setCreateTime(new Date());
prodTagReferenceList.add(prodTagReference);
});
//批量添加商品与分组标签的关系
prodTagReferenceService.saveBatch(prodTagReferenceList);
}
//删除商品原有的sku对象集合
skuMapper.delete(new LambdaQueryWrapper<Sku>()
.eq(Sku::getProdId,prodId)
);
//获取商品sku对象集合
List<Sku> skuList = prod.getSkuList();
//判断商品sku对象集合是否有值
if (!CollectionUtils.isEmpty(skuList) && skuList.size() != 0) {
//循环遍历商品sku对象集合
skuList.forEach(sku -> {
sku.setProdId(prodId);
sku.setActualStocks(sku.getStocks());
sku.setStocks(0);
sku.setVersion(0);
sku.setRecTime(new Date());
sku.setUpdateTime(new Date());
sku.setIsDelete(0);
});
//批量添加商品sku对象集合
skuService.saveBatch(skuList);
}
//修改商品信息
Integer status = prod.getStatus();
if (1 == status) {
prod.setPutawayTime(new Date());
}
prod.setUpdateTime(new Date());
return prodMapper.updateById(prod)>0;
}
@ApiOperation("批量删除xxxx")
@DeleteMapping("{ids}")
@PreAuthorize("hasAuthority('模块权限:权限:delete')")
public ResponseEntity<Void> deleteSysUser(@PathVariable List<Long> ids) {
'xxxx'Service.removeByIds(ids);
return ResponseEntity.ok().build();
}
@Override
@Transactional(rollbackFor = RuntimeException.class)
@CacheEvict(key = xxxConstant.xxx)
public boolean removeByIds(Collection<? extends Serializable> idList) {
//删除指定表2对应的权限数据
'表2xxxx'Mapper.delete(new LambdaQueryWrapper<表2实体类>()
.in('表2xxxx'::getRoleId,idList)
);
return 'xxxx'Mapper.deleteBatchIds(idList)==idList.size();
}
================================================================================================
@Override
public CartVo selectUserCartVoInfo(String userId) {
CartVo cartVo = new CartVo();
//根据用户id查询购物车记录
List<Basket> basketList = basketMapper.selectList(new LambdaQueryWrapper<Basket>()
.eq(Basket::getUserId, userId)
.orderByDesc(Basket::getBasketDate)
);
//判断用户购物车记录是否有值
if (CollectionUtils.isEmpty(basketList) || basketList.size() == 0) {
return cartVo;
}
//创建购物车店铺对象集合
List<ShopCart> shopCartList = new ArrayList<>();
//循环遍历购物车记录
basketList.forEach(basket -> {
Long basketId = basket.getBasketId();
Integer basketCount = basket.getBasketCount();
Long shopId = basket.getShopId();
Long skuId = basket.getSkuId();
//判断当前购物车商品的店铺标识是否在之前的店铺对象集合中存在
List<ShopCart> oneShopCart = shopCartList.stream()
.filter(shopCart -> shopCart.getShopId().equals(shopId))
.collect(Collectors.toList());
//如果oneShopCart集合有值:说明当前购物车商品条目对象所在的购物车店铺对象是存在的,否则相反
if (CollectionUtils.isEmpty(oneShopCart) || oneShopCart.size() == 0) {
//说明:新的购物车店铺对象
//创建购物车店铺对象
ShopCart shopCart = new ShopCart();
//创建购物车商品条目对象集合
List<CartItem> cartItemList = new ArrayList<>();
//创建购物车商品条目对象
CartItem cartItem = new CartItem();
cartItem.setBasketId(basketId);
cartItem.setBasketCount(basketCount);
//远程接口调用:根据商品skuId查询商品sku对象
List<Sku> skuList = basketProdFeign.getSkuListByIds(Arrays.asList(skuId));
if (CollectionUtils.isEmpty(skuList) || skuList.size() == 0) {
throw new RuntimeException("服务器开小差了");
}
Sku sku = skuList.get(0);
//将商品sku对象对应的属性值copy到购物车商品条目对象属性中
BeanUtils.copyProperties(sku,cartItem);
cartItemList.add(cartItem);
shopCart.setShopId(shopId);
shopCart.setShopCartItems(cartItemList);
shopCartList.add(shopCart);
} else {
//说明:存在,获取之前的购物车店铺对象
//获取之前的购物车店铺对象
ShopCart shopCart = oneShopCart.get(0);
//获取当前购物车记录所在的购物车店铺对象的商品条目对象集合
List<CartItem> shopCartItems = shopCart.getShopCartItems();
//将当前购物车记录的商品条目对象添加到之前的集合中
//创建购物车商品条目对象
CartItem cartItem = new CartItem();
cartItem.setBasketId(basketId);
cartItem.setBasketCount(basketCount);
//远程接口调用:根据商品skuId查询商品sku对象
List<Sku> skuList = basketProdFeign.getSkuListByIds(Arrays.asList(skuId));
if (CollectionUtils.isEmpty(skuList) || skuList.size() == 0) {
throw new RuntimeException("服务器开小差了");
}
Sku sku = skuList.get(0);
//将商品sku对象对应的属性值copy到购物车商品条目对象属性中
BeanUtils.copyProperties(sku,cartItem);
shopCartItems.add(cartItem);
shopCart.setShopCartItems(shopCartItems);
}
});
cartVo.setShopCarts(shopCartList);
return cartVo;
}
/**
* 用户提交订单:
* 1.判断请求的来源,是否要清除购物车中的记录
* 2.修改商品prod和sku的库存数量 -> 返回扣减商品库存数量对象
* 3.生成订单(写数据到order和order_item表)
* 4.写延迟队列(解决:订单超时未支付问题)
*
*
* @param userId
* @param orderVo
* @return
*/
@Override
@Transactional(rollbackFor = RuntimeException.class)
public String submitOrder(String userId, OrderVo orderVo) {
//获取订单请求来源
Integer source = orderVo.getSource();
//判断订单来源
if (1 == source) {
//说明:订单请求来自于购物车页面,所以我们需要将用户购买的商品从购物车中清除掉
deleteUserCart(userId,orderVo);
}
//修改商品prod和sku库存数量-> 返回商品prod和sku扣减库存数量对象
ChangeStock changeStock = changeProdAndSkuStock(orderVo);
//生成全局唯一的订单编号:使用雪花算法
String orderNumber = generateOrderNumber();
//写订单(写订单表和订单商品条目表)
writeOrder(userId,orderNumber,orderVo);
//写延迟队列
sendMsMsg(orderNumber,changeStock);
return orderNumber;
}
private void sendMsMsg(String orderNumber, ChangeStock changeStock) {
//将数据转换为json格式的字符串
JSONObject jsonObject = new JSONObject();
jsonObject.put("orderNumber",orderNumber);
jsonObject.put("changeStock",changeStock);
//将数据json对象转换为json格式的字符串存放到消息队列
rabbitTemplate.convertAndSend(QueueConstant.ORDER_MS_QUEUE,jsonObject.toJSONString());
}
@Transactional(rollbackFor = RuntimeException.class)
public void writeOrder(String userId, String orderNumber, OrderVo orderVo) {
StringBuffer prodNames = new StringBuffer();
List<OrderItem> allOrderItems = new ArrayList<>();
//获取订单店铺对象集合
List<ShopOrder> shopOrderList = orderVo.getShopCartOrders();
//循环遍历订单店铺对象集合
shopOrderList.forEach(shopOrder -> {
//获取店铺的商品条目对象集合
List<OrderItem> orderItemList = shopOrder.getShopCartItemDiscounts();
//循环遍历店铺订单商品条目对象集合
orderItemList.forEach(orderItem -> {
orderItem.setOrderNumber(orderNumber);
prodNames.append(orderItem.getProdName()).append(",");
allOrderItems.add(orderItem);
});
});
//批量添加订单商品条目对象集合
orderItemService.saveBatch(allOrderItems);
//生成订单表
Order order = new Order();
order.setProdName(prodNames.toString());
order.setUserId(userId);
order.setOrderNumber(orderNumber);
order.setTotal(orderVo.getTotal());
order.setActualTotal(orderVo.getActualTotal());
order.setPayType(1);
order.setRemarks(orderVo.getRemark());
order.setStatus(1);
order.setFreightAmount(orderVo.getTransfee());
order.setAddrOrderId(orderVo.getUserAddr().getAddrId());
order.setProductNums(orderVo.getTotalCount());
order.setCreateTime(new Date());
order.setUpdateTime(new Date());
order.setIsPayed(0);
order.setDeleteStatus(0);
order.setRefundSts(0);
order.setReduceAmount(orderVo.getShopReduce());
orderMapper.insert(order);
}
private String generateOrderNumber() {
return snowflake.nextIdStr();
}
private ChangeStock changeProdAndSkuStock(OrderVo orderVo) {
List<SkuChange> skuChangeList = new ArrayList<>();
List<ProdChange> prodChangeList = new ArrayList<>();
//获取订单店铺对象集合
List<ShopOrder> shopOrderList = orderVo.getShopCartOrders();
//循环遍历订单店铺对象集合
shopOrderList.forEach(shopOrder -> {
//获取店铺的订单商品条目对象集合
List<OrderItem> orderItemList = shopOrder.getShopCartItemDiscounts();
//循环遍历店铺订单商品条目对象集合
orderItemList.forEach(orderItem -> {
Integer prodCount = orderItem.getProdCount()*-1;
Long prodId = orderItem.getProdId();
Long skuId = orderItem.getSkuId();
//判断当前商品条目对象的商品prodId是否已经存在于商品prod扣减库存数量对象集合中
List<ProdChange> prodChanges = prodChangeList.stream()
.filter(prodChange -> prodChange.getProdId().equals(prodId))
.collect(Collectors.toList());
//判断这个集合是否有值
if (CollectionUtils.isEmpty(prodChanges) || prodChanges.size() == 0) {
//说明:当前商品prodId是不存在于商品prod扣减库存数量对象集合中的
SkuChange skuChange = new SkuChange(skuId, prodCount);
ProdChange prodChange = new ProdChange(prodId, prodCount);
skuChangeList.add(skuChange);
prodChangeList.add(prodChange);
} else {
//说明:当前商品prodId是存在于商品prod扣减库存数量对象集合中的
SkuChange skuChange = new SkuChange(skuId, prodCount);
skuChangeList.add(skuChange);
//获取之前的
ProdChange prodChange = prodChanges.get(0);
//计算商品扣减库存总数量
int finalCount = prodChange.getCount() + prodCount;
prodChange.setCount(finalCount);
}
});
});
//创建商品prod和sku扣减库存数量对象
ChangeStock changeStock = new ChangeStock(prodChangeList,skuChangeList);
//远程调用:修改商品prod和sku库存数量
orderProdFeign.updateProdAndSkuStock(changeStock);
return changeStock;
}
private void deleteUserCart(String userId, OrderVo orderVo) {
List<Long> skuIdList = new ArrayList<>();
//获取所有的订单店铺对象集合
List<ShopOrder> shopOrderList = orderVo.getShopCartOrders();
//循环遍历订单店铺对象集合
shopOrderList.forEach(shopOrder -> {
//获取订单店铺对象的订单商品条目对象集合
List<OrderItem> orderItemList = shopOrder.getShopCartItemDiscounts();
//循环遍历订单商品条目对象集合(目的:获取每一个订单商品对象的skuId)
orderItemList.forEach(orderItem -> skuIdList.add(orderItem.getSkuId()));
});
//远程接口:删除用户购买商品在购物车中的记录
Map<String,Object> map = new HashMap<>();
map.put("userId",userId);
map.put("skuIdList",skuIdList);
if (!orderBasketFeign.deleteUserBasket(map)) {
throw new RuntimeException("用户提交订单:删除购物车中商品失败");
}
}
@Override
public CartTotalAmount calculateCartTotalAmount(List<Long> basketIdList) {
CartTotalAmount cartTotalAmount = new CartTotalAmount();
//判断购物车标识集合是否有值
if (CollectionUtils.isEmpty(basketIdList) || basketIdList.size() == 0) {
return cartTotalAmount;
}
//根据购物车标识查询购物车记录
List<Basket> basketList = basketMapper.selectBatchIds(basketIdList);
//从购物车集合中获取商品skuId集合
List<Long> skuIdList = basketList.stream().map(Basket::getSkuId).collect(Collectors.toList());
//远程调用:根据商品skuId集合查询商品sku对象集合
List<Sku> skuList = basketProdFeign.getSkuListByIds(skuIdList);
if (CollectionUtils.isEmpty(skuList) || skuList.size() == 0) {
throw new RuntimeException("服务器开小差了");
}
List<BigDecimal> oneSkuTotalAmounts = new ArrayList<>();
//循环遍历购物车集合
basketList.forEach(basket -> {
Integer basketCount = basket.getBasketCount();
Long skuId = basket.getSkuId();
//从商品sku对象集合中过滤出与当前购物车记录中的商品skuId一致的商品sku对象
Sku sku1 = skuList.stream()
.filter(sku -> sku.getSkuId().equals(skuId))
.collect(Collectors.toList()).get(0);
//计算单个商品总金额
BigDecimal oneSkuTotalAmount = sku1.getPrice().multiply(new BigDecimal(basketCount));
oneSkuTotalAmounts.add(oneSkuTotalAmount);
});
//计算所有单个商品总金额的和
BigDecimal allSkuTotalAmount = oneSkuTotalAmounts.stream().reduce(BigDecimal::add).get();
cartTotalAmount.setTotalMoney(allSkuTotalAmount);
cartTotalAmount.setFinalMoney(allSkuTotalAmount);
//计算运费:单笔金额满99元免运费,否则运费6元
if (allSkuTotalAmount.compareTo(new BigDecimal(99)) == -1) {
cartTotalAmount.setTransMoney(new BigDecimal(6));
cartTotalAmount.setFinalMoney(allSkuTotalAmount.add(new BigDecimal(6)));
}
return cartTotalAmount;
}
@Override
public ProdCommOverview selectProdCommOverview(Long prodId) {
//查询商品评论总数量
Integer number = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
.eq(ProdComm::getProdId, prodId)
.eq(ProdComm::getStatus, 1)
);
//查询商品好评数量
Integer praiseNumber = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
.eq(ProdComm::getProdId, prodId)
.eq(ProdComm::getStatus, 1)
.eq(ProdComm::getEvaluate,0)
);
//查询商品中评数量
Integer secondaryNumber = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
.eq(ProdComm::getProdId, prodId)
.eq(ProdComm::getStatus, 1)
.eq(ProdComm::getEvaluate,1)
);
//查询商品差评数量
Integer negativeNumber = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
.eq(ProdComm::getProdId, prodId)
.eq(ProdComm::getStatus, 1)
.eq(ProdComm::getEvaluate,2)
);
//查询商品有图的评论数量
Integer picNumber = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
.eq(ProdComm::getProdId, prodId)
.eq(ProdComm::getStatus, 1)
.isNotNull(ProdComm::getPics)
);
//计算商品的好评率 = 好评数量 / 评论总数量
BigDecimal positiveRating = BigDecimal.ZERO;
if (0 != number) {
positiveRating = new BigDecimal(praiseNumber)
.divide(new BigDecimal(number), 2, RoundingMode.HALF_DOWN)
.multiply(new BigDecimal(100));
}
return ProdCommOverview.builder()
.praiseNumber(praiseNumber)
.secondaryNumber(secondaryNumber)
.negativeNumber(negativeNumber)
.number(number)
.positiveRating(positiveRating)
.picNumber(picNumber)
.build();
}
@Override
public Page<ProdComm> selectProdCommPageByProdId(Long prodId, Long evaluate, Page<ProdComm> page) {
//根据条件分页查询商品评论
page = prodCommMapper.selectPage(page,new LambdaQueryWrapper<ProdComm>()
.eq(ProdComm::getProdId,prodId)
.eq(ProdComm::getStatus,1)
.eq(0==evaluate||1==evaluate||2==evaluate,ProdComm::getEvaluate,evaluate)
.isNotNull(3==evaluate,ProdComm::getPics)
.orderByDesc(ProdComm::getRecTime)
);
//从商品评论分页对象中获取评论记录
List<ProdComm> prodCommList = page.getRecords();
//判断是否有值
if (CollectionUtils.isEmpty(prodCommList) || prodCommList.size() == 0) {
return page;
}
//从评论记录集合中获取用户id
List<String> userIdList = prodCommList.stream().map(ProdComm::getUserId).collect(Collectors.toList());
//远程接口:根据用户id集合查询用户对象集合
List<User> userList = prodCommUserFeign.getUserListByUserIds(userIdList);
if (CollectionUtils.isEmpty(userList) || userList.size() == 0) {
throw new RuntimeException("服务器开小差了");
}
//循环遍历评论集合
prodCommList.forEach(prodComm -> {
//从用户对象集合中过滤出与当前评论中的用户id一致的用户对象
User user1 = userList.stream()
.filter(user -> user.getUserId().equals(prodComm.getUserId()))
.collect(Collectors.toList()).get(0);
//获取用户昵称
StringBuffer nickName = new StringBuffer(user1.getNickName());
nickName.replace(1,nickName.length()-1,"***");
prodComm.setNickName(nickName.toString());
prodComm.setPic(user1.getPic());
});
return page;
}