Mybatis中使用in()查询

2年前 (2022) 程序员胖胖胖虎阿
185 0 0

这篇文章我会演示几种mybatis中使用in查询的方式。

1 数组、字符串

2 集合

3 使用Myabtis-plus框架的条件构造器来实现

我们在mysql中使用in查询的方式是这样的

Mybatis中使用in()查询

 那在mybatis中我们使用<foreach>标签来实现包含查询

1 使用数组方式

Mapper:

Mybatis中使用in()查询

 Mapper.xml:

<select id="studentList" resultType="com.ywt.springboot.model.Student">
        select *
        from student
        where id in
        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

 :foreach中的 collection标签中为array,item是遍历ids中的每个元素,默认为item可以自定义。

测试类:

Mybatis中使用in()查询

我们可以使用字符串来接收参数,使用逗号分隔每个参数,然后把分隔后的参数放到集合中。

 Mybatis中使用in()查询

 2 使用List集合的方式

Mapper:

Mybatis中使用in()查询

 Mapper.xml

<select id="studentList" resultType="com.ywt.springboot.model.Student">
        select *
        from student
        where id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

 使用list方式collection的value必须为list

 测试:

Mybatis中使用in()查询

3 第三种我们使用Mybatis-plus框架的条件构造器来进行查询

@Test
    void Test(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.in("id",7,9);
        List<Student> students = studentMapper.selectList(qw);
        System.out.println(students.toString());
    }

条件构造器相关的方法在我另一篇博客,总结了常用的多种方法,以供大家参考:

Mybatis-plus的条件构造器详细使用教程_保加利亚的风的博客-CSDN博客_mybatis构造器

 测试结果:

[Student(id=7, name=蔡徐坤, age=18), Student(id=9, name=金科徐, age=18)]
版权声明:程序员胖胖胖虎阿 发表于 2022年11月2日 下午4:48。
转载请注明:Mybatis中使用in()查询 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...