Mybatis中使用in()查询

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

1 数组、字符串

2 集合

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

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

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

1 使用数组方式

Mapper:

 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可以自定义。

测试类:

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

 

 2 使用List集合的方式

Mapper:

 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

 测试:

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)]

  • 18
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值