mybatis接收参数为对象,其中包含List<string>处理

问题描述:
很多人在mybatis的xml中用到传参数实体类中包含list<string>,在xml中用foreach遍历时候,会犯错误,如下图:


image.png

实体类代码:

public class AlarmConditionDTO {
    private List<String> orgIds;  
    private List<String> tagIds;   
    private String alertType;
    private Long startTime;
    private Long endTime;
    private int pageNum;
    private int pageSize;
    private String deviceName;
    private String searchConditionTime;
}

mapper,dao层:

List<Map<String,String>> selectDeviceCountByCondition(AlarmConditionDTO alarmConditionDTO);

错误写法上图解释:
在xml中想遍历list<String>这个值,写成
<foreach collection="orgIds" open="(" close=")" separator="," item="item">
#{orgIds}
</foreach>
这样会报错,list类型参数无法正确解析。
解决办法有两种:
第一:

<select id="selectDeviceCountByCondition" resultType="java.util.Map">
        SELECT
            device_type deviceType,count(device_type) count
        FROM
            (select DISTINCT obj_id obj_id from md_tag_target_relation_device where 1=1
        <if test="tagIds != null and tagIds.size()>0">
            and tag_id IN
            <foreach collection="orgIds" index="index" open="(" close=")" separator="," item="item">
                #{tagIds[${index}],jdbcType=VARCHAR}
            </foreach>
        </if>
        ) td
        LEFT JOIN
            md_resource_device d ON td.obj_id = d.uuid
        where 1=1 and device_name is not null
        <if test="orgIds != null and orgIds.size()>0">
            and d.region_code IN
            <foreach collection="orgIds" index="index" open="(" close=")" separator="," item="item">
                #{orgIds[${index}],jdbcType=VARCHAR}
            </foreach>
        </if>
        group by
            d.device_type
    </select>

这中写法意思是,取这个数组中的每一个,因为字段是List<String>。
第二种:
修改mapper接口方法的参数,增加注解 @Param("aa") AlarmConditionDTO alarmConditionDTO
param中名字随便起,这里起aa,xml中写:

<if test="aa.orgIds!= null and aa.orgIds.size()>0">
            and d.region_code IN
            <foreach collection="aa.orgIds" index="index" open="(" close=")" separator="," item="item">
                #{item}
            </foreach>
        </if>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容