spring data jpa之資料增刪改查程式碼優化
阿新 • • 發佈:2018-12-06
Spring data jpa為減少查詢資料庫次數,先將符合條件的資料查出來,返回的是一個list集合,遍歷集合將資料裝入map中,根據需要設定key,value,然後判斷map是否包含某個key或者value以此判斷資料是否在資料庫中已經存在。這樣減少了訪問資料庫的次數,減小了伺服器壓力,將大部分操作放進了記憶體中進行。
最後: 一定要記住,除非沒有其他方法實現,否則一定不要把增刪改查寫在for迴圈裡面,資料量一大,其速度可想而知。
以下是我專案中的一個修改方法:
/** * @param memberInfoList */ @Override public void modify(List<StockMemberInfo> memberInfoList,Unit unit) { SimpleSpecificationBuilder<StockShare> builder = new SimpleSpecificationBuilder<>(); builder.add("unit", SpecificationOperator.Operator.eq.name(), unit.getId()); List<StockShare> stockShareList = stockShareService.findList(builder.generateSpecification(),null); Map<String, StockShare> map = new HashMap<>(16); SimpleSpecificationBuilder<StockMemberInfo> builder2 = new SimpleSpecificationBuilder<>(); builder2.add("unitCode", SpecificationOperator.Operator.likeL.name(), unit.getUnitCode()); List<StockMemberInfo> stockMemberInfoList = stockMemberInfoService.findList(builder2.generateSpecification(), null); Map<String, StockMemberInfo> memberInfoMap = new HashMap<>(16); List<StockMemberInfo> list = new ArrayList<>(); for (StockShare stockShare : stockShareList) { map.put(stockShare.getStockCategory().getName(),stockShare); } for (StockMemberInfo stockMemberInfo : stockMemberInfoList) { memberInfoMap.put(stockMemberInfo.getUniqueField(), stockMemberInfo); } for (StockMemberInfo stockMemberInfo : memberInfoList) { if (map.get(stockMemberInfo.getStockShare().getStockCategory().getName()) == null) { throw new RuntimeException("你還未進行份額計算"); } String uniqueField = stockMemberInfo.getMemberInfo().getId()+"-"+map.get(stockMemberInfo.getStockShare().getStockCategory().getName()).getId(); if (memberInfoMap.containsKey(uniqueField)) { StockMemberInfo s = memberInfoMap.get(uniqueField); s.setStockNum(stockMemberInfo.getStockNum()); list.add(s); } } stockMemberInfoService.save(list); }