Explorar o código

将GoodsAttrServiceImpl.java中的findByGoodsId方法里的循环调用数据库的方法优化

liu hai 2 meses
pai
achega
e86ac8376d

+ 21 - 3
src/main/java/com/sqx/modules/goods/service/impl/GoodsAttrServiceImpl.java

@@ -11,7 +11,10 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 
 @Service
 public class GoodsAttrServiceImpl extends ServiceImpl<GoodsAttrDao, GoodsAttr> implements GoodsAttrService {
@@ -71,10 +74,25 @@ public class GoodsAttrServiceImpl extends ServiceImpl<GoodsAttrDao, GoodsAttr> i
     @Override
     public List<GoodsAttr> findByGoodsId(Long goodsId) {
         List<GoodsAttr> list = findAllByGoodsId(goodsId);
-        for (GoodsAttr goodsAttr : list) {
-            List<GoodsAttrValue> valueList = goodsAttrValueService.findAllByGoodsId(goodsAttr.getGoodsId());
-            goodsAttr.setAttrValue(valueList);
+        List<Long> goodsIdList = list.stream().map(GoodsAttr::getGoodsId).collect(Collectors.toList());
+        if (goodsIdList.size()>0) {
+            List<GoodsAttrValue> goodsAttrValues = goodsAttrValueService.list(new QueryWrapper<GoodsAttrValue>().in("goods_id", goodsIdList));
+            Map<Long, List<GoodsAttrValue>> map = goodsAttrValues.stream().collect(Collectors.toMap(
+                    GoodsAttrValue::getGoodsId,
+                    goodsAttrValue -> new ArrayList<>(Collections.singletonList(goodsAttrValue)),
+                    (oldList, newList) -> {
+                        oldList.addAll(newList);
+                        return oldList;
+                    }
+            ));
+            for (GoodsAttr goodsAttr : list) {
+//                List<GoodsAttrValue> valueList = goodsAttrValueService.findAllByGoodsId(goodsAttr.getGoodsId());
+                goodsAttr.setAttrValue(map.get(goodsAttr.getGoodsId()
+                ));
+
+            }
         }
+
         return list;
     }