Mybatis多个集合的迭代处理

在使用这个功能是需要特别注意以下规则:

1. 当查询的参数只有一个

 A. 如果参数的类型是List, 则在使用时,collection属性要必须指定为 list

       findByIds(List<Long> ids)

<select id="findByIdsMap" resultMap="BaseResultMap">
         Select
         <include refid="Base_Column_List" />
         from sys_user where user_id in
                  <foreach item="item" index="index" collection="list"
                         open="(" separator="," close=")">
                        #{item}
                </foreach>
  </select>

B. 如果参数的类型是Array,则在使用时,collection属性要必须指定为 array

   findByIds(Long[] ids)

<select id="findByIdsMap" resultMap="BaseResultMap">
                 select
                 <include refid="Base_Column_List" />
          from sys_user where user_id in
                  <foreach item="item" index="index" collection="array"
                         open="(" separator="," close=")">
                        #{item}
                </foreach>
  </select>
2、

  当查询的参数有多个时,例如 findByIds(String name, Long[] ids)//这种方式不推荐使用

 这种情况需要特别注意,在传参数时,一定要改用Map方式, 这样在collection属性可以指定名称

  下面是一个示例

 Map<String, Object> params = new HashMap<String, Object>(2);
        params.put("name", name);
         params.put("shxt", ids);
        mapper.findByIdsMap(params);
 
    <select id="findByIdsMap" resultMap="BaseResultMap">
                 select
                 <include refid="Base_Column_List" />
          from sys_user where user_id in
                  <foreach item="item" index="index" collection="shxt"
                         open="(" separator="," close=")">
                        #{item}
                </foreach>
   </select>

3、本人实际使用例子

 @Override
    public List<PointsSummaryForMonths> pointsForPduMonthForIN() {

        List<CustomPdu> list = customPduMapper.getPidFromCustomPdu();
        List<Integer> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            int pduId = list.get(i).getPid();
            list1.add(pduId);
        }

        List<String> list2=DateUtil.getMonthList();
        Map<String, Object> pduIdMap = new HashMap<>();
        pduIdMap.put("listone", list1);
        pduIdMap.put("listtwo",list2);

        //Map<String,Object> monthMap=new HashMap<>();
        //  monthMap= DateUtil.getDateMap();
        return pointsSummaryForMonthsMapper.pointsForPduMonthForIN(pduIdMap);
    }
List<PointsSummaryForMonths> pointsForPduMonthForIN(Map map);
WHERE
	jira.PROJECT in
     <foreach collection="listone" index="index" item="item" open="(" close=")" separator=",">
        #{item}
    </foreach>
    AND it.ID IN ("10001", "10102", "10100")
AND jira.issuestatus = "10001"
GROUP BY  pro.pname,
	date_format(doneTable.doneDate, '%Y-%m'))as tabletwo
    where tabletwo.month in
        <foreach collection="listtwo" index="index" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
  </select>


猜你喜欢

转载自blog.csdn.net/intelrain/article/details/80632535