Mybatis in查询List或数组 场景实例

1.mybatis in 查询List时

业务代码示例如下:

List<String> list=new ArrayList<String>();

...;//向list中填装参数值

//list为必传参数集时,判断如果该list为空,没有参数值,则填装一个-1或其他保证该表不会查询出的参数值;
//如果list为非必传参数集时,则下面if判断可以省去;
if(list.size()==0){
    list.add("-1");
}

HashMap<String,Object> params=new HashMap<String,Object>();
params.put("list",list);
List<HashMap<String,Object>> rList=dao.queryParams(params);

mybatis中相应sql写法示例如下:

<select id="queryParams" resultType="HashMap">
    select * from cga_case a 
    <where>
        <if test="list != null and list.size()>0">//注意:此处不能写list!=''要写成list.size()>0,不然会报错
        AND a.case_id IN
        <foreach item="item" index="index" collection="list" open="("  close=")" separator=",">  
          #{item}   
        </foreach>  
    </if>
    </where>
</select>

2.mybatis in查询 数组时

业务代码示例如下:

String[] arr=new String[]{...};
//arr为必传参数集时,判断如果该arr为空,没有参数值,则填装一个-1或其他保证该表不会查询出数据的参数值;
//如果arr为非必传参数集时,则下面if判断可以省去;
if(arr.length==0){
    arr=new String[]{"-1"};
}


HashMap<String,Object> params=new HashMap<String,Object>();
params.put("arr",arr);
List<HashMap<String,Object>> rList=dao.queryParams(params);

mybatis中相应sql写法示例如下:

<select id="queryParams" resultType="HashMap">
    select * from cga_case a 
    <where>
        <if test="arr != null and arr.length>0">
        AND a.case_id IN
        <foreach item="item" index="index" collection="arr" open="("  close=")" separator=",">  
          #{item}   
        </foreach>  
    </if>
    </where>
</select>

猜你喜欢

转载自blog.csdn.net/fantasy522272820/article/details/78528346