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