一、起因

有下面这样一段代码,在for循环中调用SQL,然后将查询到的值回填;导致,for循环中会调用很多SQL,速度很慢。

text
1 2 3 4 5 6 7
for (DeclareCategory dc :list){
     ParameterVO parameter = new ParameterVO();
     parameter.setId(dc.getId());
     List<Stage> stages = stageMapper.getdeclaryStagePing(parameter);
     dc.setStage(stages);
    }
二、优化方案

可以将参数提前封装好,进行批量查询,再将查询的结果进行匹配回填,这样能大大提高效率,数据量大的情况下效果更明显。

三、实施方案

1、将需要的参数进行封装为List

text
1 2 3 4 5 6 7 8 9 10 11 12
public ParameterVO packeParam(List<DeclareCategory> list){
   //提取出所有DC的id
   List<Long> dcIds = new ArrayList<>();
   for (DeclareCategory dc : list){
     dcIds.add(dc.getId());
   }
   //封装传入参数
   ParameterVO parameter=new ParameterVO();
   parameter.setArray(dcIds);
   return parameter;
  }

2、创建查询结果的返回实体类

text
1 2 3 4 5 6 7 8 9
public class ResultStageVO {

   private Long declareCategoryId;

   private List<Stage> list;
   
   //get、set自行补齐
   }

3、mapper的xml文件

封装结果集

text
1 2 3 4 5 6 7 8 9
<resultMap type="com.ruoyi.declare.vo.ResultStageVO" id="StageResultList">
   <result column="declare_category_id" property="declareCategoryId"/>
   <collection property="list" ofType="com.ruoyi.common.core.domain.entity.Stage">
      <result property="id" column="id"/>
      <result property="projectId" column="project_id"/>
      ......
   </collection>
</resultMap>

ql语句,用正常的foreach循环即可

text
1 2 3 4 5 6 7 8 9 10 11 12 13
SELECT
         s.*,
         p.*
      FROM
         project p,
      WHERE
         p.id = s.project_id
         AND
         <foreach item="array" collection="array" open="(" separator="or" close=")">
            p.declare_category_id = ${array}
         </foreach>
      GROUP BY s.id

4、mapper文件

text
1 2
List<ResultStageVO> getDeclaryStageShen(ParameterVO parameter);

5、对结果集进行匹配合并
具体查看这里

原文地址:https://blog.csdn.net/greenhandp/article/details/124126852?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168475003816800184167725%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168475003816800184167725&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-5-124126852-null-null.142^v87^insert_down1,239^v2^insert_chatgpt&utm_term=java%E4%BC%98%E5%8C%96