怎么才能把代码写好呢?
今天在做项目的时候遇到了很平常的一个功能——新增商品数据,但是商品对应字段很多,与之有关系的还有很多其他表中的信息,是一对多的关系。
写的时候就不是很满意了,但是先完成这个功能也很重要。
@Transactional
@Override
public boolean savePmsProductDto(PmsProductDto pmsProductDto) {
boolean save = this.save(pmsProductDto);
Long id ;
if(save){
id = pmsProductDto.getId();
switch (pmsProductDto.getPromotionType()){
case 2: // 使用会员价
List<PmsMemberPrice> memberPriceList = pmsProductDto.getMemberPriceList();
for (PmsMemberPrice pmsMemberPrice: memberPriceList) {
pmsMemberPrice.setProductId(id);
}
pmsMemberPriceService.saveBatch(memberPriceList);
case 3: // 使用阶梯价格
List<PmsProductLadder> productLadderList = pmsProductDto.getProductLadderList();
for (PmsProductLadder pmsProductLadder: productLadderList) {
pmsProductLadder.setProductId(id);
}
pmsProductLadderService.saveBatch(productLadderList);
case 4: // 使用满减价格
List<PmsProductFullReduction> productFullReductionList = pmsProductDto.getProductFullReductionList();
for (PmsProductFullReduction pmsProductFullReduction: productFullReductionList) {
pmsProductFullReduction.setProductId(id);
}
pmsProductFullReductionService.saveBatch(productFullReductionList);
}
List<PmsProductAttributeValue> productAttributeValueList = pmsProductDto.getProductAttributeValueList();
for (PmsProductAttributeValue pmsProductAttributeValue: productAttributeValueList) {
pmsProductAttributeValue.setProductId(id);
}
pmsProductAttributeValueService.saveBatch(productAttributeValueList);
List<PmsSkuStock> skuStockList = pmsProductDto.getSkuStockList();
for (PmsSkuStock pmsSkuStock: skuStockList) {
pmsSkuStock.setProductId(id);
}
pmsSkuStockService.saveBatch(skuStockList);
}
return save;
}
其中的这几个List操作都是需要:1,遍历的每条数据中加入productId
2.,进行插入数据
想一想可不可以把这样的操作提出来呢?可以的。
优化之后的代码如下:
这里利用了反射。
@Transactional
@Override
public boolean savePmsProductDto(PmsProductDto pmsProductDto) {
boolean save = this.save(pmsProductDto);
Long id ;
if(save){
id = pmsProductDto.getId();
switch (pmsProductDto.getPromotionType()){
case 2: // 使用会员价
saveRelationList(pmsProductDto.getMemberPriceList(),id,pmsMemberPriceService);
case 3: // 使用阶梯价格
saveRelationList(pmsProductDto.getProductLadderList(),id,pmsProductLadderService);
case 4: // 使用满减价格
saveRelationList(pmsProductDto.getProductFullReductionList(),id,pmsProductFullReductionService);
}
saveRelationList(pmsProductDto.getProductAttributeValueList(),id,pmsProductAttributeValueService);
saveRelationList(pmsProductDto.getSkuStockList(),id,pmsSkuStockService);
}
return save;
}
private void saveRelationList(List list,Long productId,IService iService){
try{
for (Object object : list){
Method setProductIdMethod = object.getClass().getMethod("setProductId", Long.class);//利用反射
setProductIdMethod.invoke(object,productId);
}
iService.saveBatch(list);
}catch (Exception e){
throw new RuntimeException(e);
}
}
重在积累,勤于记录,经常复习。
——致自己:当你越过了这座山,那么它就不再是座山。