在MySQL中使用in查询
select * from tb_student where id in ( ? , ? , ? )
1、数组为入参
Mapper
List<Student> selectList(String[] ids);
Mapper.xml
<select id="selectList" resultType="com.demo.entity.Student">
select *
from tb_student
where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
Test
@Test
void selectList() {
String[] ids = new String[]{
"1", "2", "3"};
List<Student> list = mapper.selectList(ids);
}
日志中输出的SQL
select * from tb_student where id in ( ? , ? , ? )
2、List为入参
Mapper
List<Student> selectList(List<String> ids);
Mapper.xml
<select id="selectList" resultType="com.demo.entity.Student">
select *
from tb_student
where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
Test
@Test
void selectList() {
List<String> ids = new ArrayList<>();
ids.add("1");
ids.add("2");
ids.add("3");
List<Student> list = mapper.selectList(ids);
}
日志中输出的SQL
select * from tb_student where id in ( ? , ? , ? )
3、Mybatis-plus条件构造器为入参
Mapper
List<Student> selectList(@Param(Constants.WRAPPER) Wrapper<Student> wrapper);
Mapper.xml
<select id="selectList" resultType="com.demo.entity.Student">
select *
from tb_student
${ew.customSqlSegment}
</select>
Test
@Test
void selectList() {
List<String> ids = new ArrayList<>();
ids.add("1");
ids.add("2");
ids.add("3");
LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.in(Student::getId, ids);
List<Student> list = mapper.selectList(queryWrapper);
}
日志中输出的SQL
select * from tb_student WHERE (id IN (?,?,?))
参考文章
1、https://mouday.github.io/coding-tree/mybatis-plus/1-MyBatis-Plus.html#自定义-sql
2、Mybatis中使用in()查询