代码优化:遍历查询数据库代码优化
Posted root_zhb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了代码优化:遍历查询数据库代码优化相关的知识,希望对你有一定的参考价值。
遍历查询数据库代码优化
场景:针对遍历查询数据库的两种场景做出优化,都是将多次遍历查询改为一条查询。
把数据库层面的 IO压力 转化为 代码层面的CPU和内存压力
SQL 映射 HashMap< String, List < T > >
- 先查list,再stream分组
- 搞个头行的实体类,resultMap返回
低效代码
for(TransportPlanningLines t:lines)
List<TransportPlanningLines> transportPlanningLines = this.transportPlanningLinesRepository.select("transportPlanningNumber",t.getTransportPlanningNumber());
以先list再stream分组,优化后
//筛选出所有行id
List<String> collect = lines.stream().map(TransportPlanningLines::getTransportPlanningNumber).collect(Collectors.toList());
//查出所有得lineList
List<TransportPlanningLines> linesList = transportPlanningLinesMapper.selectTransportPlanningLines(collect);
//根据TransportPlanningNumber分组
Map<String, List<TransportPlanningLines>> collect1 = linesList.stream().collect(Collectors.groupingBy(TransportPlanningLines::getTransportPlanningNumber));
//配置合计数量
for(TransportPlanningLines t:lines)
List<TransportPlanningLines> transportPlanningLines = collect1.get(t.getTransportPlanningNumber());
SQL 映射List< HashMap< String,String> >
参考资料:https://www.cnblogs.com/newbest/p/10018685.html
此处低效代码与上面类似,优化后如下
List<Long> collect = transportPlanningLines.stream().map(TransportPlanningLines::getRequiredPlanItemLinesId).collect(Collectors.toList());
List<HashMap<String, String>> longStringHashMap = requiredPlanItemLinesMapper.selectJtMaterialCodeAndComments(collect);
for(TransportPlanningLines t:transportPlanningLines)
String manufactureFactory = t.getManufactureFactory();
String weightWay = t.getWeightWay();
String acceptanceQuantity = t.getAcceptanceQuantity().toString();
for(HashMap<String, String> map:longStringHashMap)
if(map.containsValue(t.getRequiredPlanItemLinesId()))
String jtMaterialCode = map.get("jt_material_code");
String comments = map.get("comments");
//业务代码忽略
Mapper如下
List<HashMap<String,String>> selectJtMaterialCodeAndComments(@Param("list") List<Long> list);
SQL如下
<select id="selectJtMaterialCodeAndComments" resultType="java.util.HashMap">
select
rpil.required_plan_item_lines_id,
rpil.comments,
si.jt_material_code
from scux_ynjt_required_plan_item_lines rpil
left join smdm_item si on rpil.material_code=si.item_code
WHERE
rpil.required_plan_item_lines_id in
<foreach collection="list" item="item" open="(" separator="," close=")">
#item
</foreach>
</select>
开发者涨薪指南
48位大咖的思考法则、工作方式、逻辑体系
以上是关于代码优化:遍历查询数据库代码优化的主要内容,如果未能解决你的问题,请参考以下文章