9 - 动态SQL--foreach

foreach
需要注意一点的是:
collectionset list array时,index为集合的下标, item为元素值
collectionmap时,indexkey,itemvalue
dao

List<Student> listStudents(List<Integer> list);

mapper

<select id="listStudents" resultMap="studentMapper">
        select * from `student`
        where `id` in
        <foreach collection="list" item="value" index="indexOrKey" 
                 open="(" separator="," close=")">
            #{value}
        </foreach>
    </select>

test

    @Test
    public void test() {
        SqlSession session = factory.openSession();
        try {
            StudentMapper studentMapper = session.getMapper(StudentMapper.class);
            List<Integer> listIds = new ArrayList<>();
            listIds.add(1000);
            listIds.add(10001);
            List<Student> students = studentMapper.listStudents(listIds);
            if(!students.isEmpty()){
                for (Student student:
                        students) {
                    System.out.println(student);
                }
            }else{
                System.out.println("没有查到结果!");
            }
        } finally {
            session.commit();
            session.close();
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。