MyBatis 使用foreach与其他方式的时候参数传递方式

时间:2022-12-26 00:11:34

Mapper文件:

    <select id="selectPersonByIds" parameterType="map" resultMap="baseResultMap">
        select * from person t where t.person_id in
        <foreach collection="list" item="item" open="(" close=")"
            index="index" separator=",">
            #{item}
        </foreach>
        and t.name like #{name}
    </select>

Java文件:

@Test
    public void selectPersonByIds() {
        SqlSession session = sessionFactory.openSession();
        try {
            String statement = "com.stone.mapper.PersonMapper.selectPersonByIds";
            Map<String, Object> map = new HashMap<String, Object>();
            List<Integer> ints = new ArrayList<Integer>();
            ints.add(1);
            ints.add(8);
            ints.add(9);
            map.put("list", ints);
            map.put("name", "刘备");
            List<Person> pList = session.selectList(statement, map);
            for (Person person : pList) {
                System.out.println(person);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }