2.商品修改
2.1.編輯按鈕點選事件
在商品詳情頁,每一個商品後面,都會有一個編輯按鈕:
點選這個按鈕,就會打開一個商品編輯視窗,我們看下它所綁定的點選事件:
對應的方法:
可以看到這裡發起了兩個請求,在查詢商品詳情和sku資訊。
因為在商品清單頁面,隻有spu的基本資訊:id、标題、品牌、商品分類等。比較複雜的商品詳情(spuDetail)和sku資訊都沒有,編輯頁面要回顯資料,就需要查詢這些内容。
是以,接下來我們就編寫背景接口,提供查詢服務接口。
2.2.查詢SpuDetail接口
GoodsController
需要分析的内容:
- 請求方式:GET
- 請求路徑:/spu/detail/{id}
- 請求參數:id,應該是spu的id
- 傳回結果:SpuDetail對象
@GetMapping("/spu/detail/{id}")
public ResponseEntity<SpuDetail> querySpuDetailById(@PathVariable("id") Long id) {
SpuDetail detail = this.goodsService.querySpuDetailById(id);
if (detail == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return ResponseEntity.ok(detail);
}
複制
GoodsService
public SpuDetail querySpuDetailById(Long id) {
return this.spuDetailMapper.selectByPrimaryKey(id);
}
複制
測試
2.3.查詢sku
分析
- 請求方式:Get
- 請求路徑:/sku/list
- 請求參數:id,應該是spu的id
- 傳回結果:sku的集合
GoodsController
@GetMapping("sku/list")
public ResponseEntity<List<Sku>> querySkuBySpuId(@RequestParam("id") Long id) {
List<Sku> skus = this.goodsService.querySkuBySpuId(id);
if (skus == null || skus.size() == 0) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return ResponseEntity.ok(skus);
}
複制
GoodsService
需要注意的是,為了頁面回顯友善,我們一并把sku的庫存stock也查詢出來
public List<Sku> querySkuBySpuId(Long spuId) {
// 查詢sku
Sku record = new Sku();
record.setSpuId(spuId);
List<Sku> skus = this.skuMapper.select(record);
for (Sku sku : skus) {
// 同時查詢出庫存
sku.setStock(this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
}
return skus;
}
複制
測試:
2.4.頁面回顯
随便點選一個編輯按鈕,發現資料回顯完成:
2.5.頁面送出
這裡的儲存按鈕與新增其實是同一個,是以送出的邏輯也是一樣的,這裡不再贅述。
随便修改點資料,然後點選儲存,可以看到浏覽器已經送出請求:
2.6.背景實作
接下來,我們編寫背景,實作修改商品接口。
2.6.1.Controller
- 請求方式:PUT
- 請求路徑:/
- 請求參數:Spu對象
- 傳回結果:無
/**
* 新增商品
* @param spu
* @return
*/
@PutMapping
public ResponseEntity<Void> updateGoods(@RequestBody SpuBo spu) {
try {
this.goodsService.update(spu);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
複制
2.6.2.Service
spu資料可以修改,但是SKU資料無法修改,因為有可能之前存在的SKU現在已經不存在了,或者以前的sku屬性都不存在了。比如以前記憶體有4G,現在沒了。
是以這裡直接删除以前的SKU,然後新增即可。
代碼:
@Transactional
public void update(SpuBo spu) {
// 查詢以前sku
List<Sku> skus = this.querySkuBySpuId(spu.getId());
// 如果以前存在,則删除
if(!CollectionUtils.isEmpty(skus)) {
List<Long> ids = skus.stream().map(s -> s.getId()).collect(Collectors.toList());
// 删除以前庫存
Example example = new Example(Stock.class);
example.createCriteria().andIn("skuId", ids);
this.stockMapper.deleteByExample(example);
// 删除以前的sku
Sku record = new Sku();
record.setSpuId(spu.getId());
this.skuMapper.delete(record);
}
// 新增sku和庫存
saveSkuAndStock(spu.getSkus(), spu.getId());
// 更新spu
spu.setLastUpdateTime(new Date());
spu.setCreateTime(null);
spu.setValid(null);
spu.setSaleable(null);
this.spuMapper.updateByPrimaryKeySelective(spu);
// 更新spu詳情
this.spuDetailMapper.updateByPrimaryKeySelective(spu.getSpuDetail());
}
複制
2.6.3.mapper
與以前一樣。