Mybatis 传入数组(<foreach>)

上接:Mybatis传入List,字符串数组(<foreach>)

概述

mybatis使用<foreach>标签解决传入 数组 的问题

修改 IUserMapper

public int deleteByIds(String[] ids);

修改 userMapper.xml

<update id="deleteByIds" >
    update user set status='2' where id in
    <foreach collection="array" open="(" close=")" item="it" separator=",">
        #{it}
    </foreach>
</update>

parameterType属性值:

设置为: Object[]、string[] 或者 不设置该属性

例子: parameterType="Object[]"

<foreach>标签解释:

  • foreach相当于 for 循环语句

  • 下面属性没有先后顺序

  • collection="array":由于只传递一个数组,所以此处必须是array

  • item="it":在循环时,it表示当前元素

  • open="(" :开始循环前,要拼接的字符串

  • separator="," :表示用,分隔

  • close=")" :结束循环后,要拼接的字符串

  • #{it}:此 it 是 item="it"指定的。此处表示拼接当前这个元素

执行

@Test
public void testDeleteByIds() throws IOException {

    String[] ids=new String[]{"10001","10002","10003"};

    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);

    int i=mapper.deleteByIds(ids);
    System.out.println("删除了"+i+"条记录!");
    sqlSession.close();
    inputStream.close();
}

注意下面写法

也可以配合 <where> 、<if> 标签,将 id in 写在 open 属性中

<update id="deleteByIds" >
    update user set status='2' 
    <where> 
    <if test="array!=null and array.length>0">
        <foreach collection="array" open="id in (" close=")" item="it" separator=",">
            #{it}
        </foreach>
    </if>
    </where>
</update>

隐藏巨大问题

当传递 null 或 数组长度为 0 时,

将执行的sql是:update user set status='2' ,

会改变该表所有的记录,所以一般不要这么写

测试

@Test
public void testDeleteByIds2() throws IOException {

    String[] ids=new String[]{};

    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);

    int i=mapper.deleteByIds2(ids);
//        int i=mapper.deleteByIds2(null);
    System.out.println("删除了"+i+"条记录!");
    sqlSession.close();
    inputStream.close();
}

在控制台中显示:

DEBUG [main] - ==>  Preparing: update user set status='2'

原文出处:/show_1EF6a24gyYqr.html