这篇文章我会演示几种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()); }
条件构造器相关的方法在我另一篇博客,总结了常用的多种方法,以供大家参考:
测试结果:
[Student(id=7, name=蔡徐坤, age=18), Student(id=9, name=金科徐, age=18)]
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/48499.html