美文网首页
9 - 动态SQL--foreach

9 - 动态SQL--foreach

作者: 农民工__乔Young | 来源:发表于2019-05-14 21:24 被阅读0次

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();
        }
    }

相关文章

网友评论

      本文标题:9 - 动态SQL--foreach

      本文链接:https://www.haomeiwen.com/subject/doxyaqtx.html