List<StockInfo> stockInfos = stockInfoRepository.findAll();
Map<String, StockInfo> map = new HashMap<>();
//使用java代码实现通过itemId(商品id)和houseId(仓库id)分组计算数量
stockInfos.forEach(stockInfo -> {
String key = stockInfo.getItemId() + "" + stockInfo.getHouseId();
if (map.containsKey(key)) {
Integer stockSkuNum = stockInfo.getNum();
StockInfo sir = map.get(key);
sir.setNum(sir.getNum() + stockSkuNum);
} else {
StockInfo stockInfo2 = new StockInfo();
stockInfo2.setHouseId(stockInfo.getHouseId());
stockInfo2.setItemId(stockInfo.getItemId());
stockInfo2.setNum(stockInfo.getNum());
//map.put(key, stockInfo);// 罪魁祸首不要put循环的对象stockInfo,不然会直接改变数据库的值
map.put(key, stockInfo2);
}
});
return new ArrayList<>(map.values());