Mybatis 传入List(<foreach>)

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

概述

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

修改 IUserMapper

public List<User> selectByIds(List ids);

修改 userMapper.xml

<select id="selectByIds" resultMap="UserMap">
    select id,username,password from user where id in
    <foreach collection="list" open="(" close=")" item="it" separator=",">
        #{it}
    </foreach>
</select>

parameterType属性值:

设置为list 或 java.util.List 或 不设置该属性

例子: parameterType="list"

<foreach>标签解释:

  • foreach相当于 for 循环语句

  • 下面属性没有先后顺序

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

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

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

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

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

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

执行

@Test
public void testSelectByIds() throws IOException {

    List ids=new ArrayList();
    ids.add("10001");
    ids.add("10002");
    ids.add("10003");

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

    List<User> list=mapper.selectByIds(ids);
    for(User u:list) {
        String info = String.format("id:%s,用户名:%s,密码:%s", u.getId(), u.getUsername(), u.getPassword());
        System.out.println(info);
    }
    sqlSession.close();
    inputStream.close();
}

注意下面写法

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

<select id="selectByIds" resultMap="UserMap">
    select id,username,password from user 
    <where> 
    <if test="list!=null and list.size()>0">
        <foreach collection="list" open="id in (" close=")" item="it" separator=",">
            #{it}
        </foreach>
    </if>
    </where>
</select>

隐藏巨大问题

当传递 null 或 list长度为 0 时,

将执行的sql是:select id,username,password from user ,

会查询该表所有的记录,如果该表的记录很多,会给数据库、java程序造成巨大压力,所以一般不要这么写

测试

@Test
public void testSelectByIds2() throws IOException {

    List ids=new ArrayList();

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

//        List<User> list=mapper.selectByIds2(ids);
    List<User> list=mapper.selectByIds2(null);
    for(User u:list) {
        String info = String.format("id:%s,用户名:%s,密码:%s", u.getId(), u.getUsername(), u.getPassword());
        System.out.println(info);
    }
    sqlSession.close();
    inputStream.close();
}

在控制台中显示:

DEBUG [main] - ==>  Preparing: select id,username,password from user

原文出处:/show_1EF6a2CVAEI1.html