目录
  • 1、数组为入参
  • 2、List为入参
  • 3、Mybatis-plus条件构造器为入参
  • 参考文章


在MySQL中使用in查询

select * from tb_student where id in ( ? , ? , ? )
  • 1.

1、数组为入参

Mapper

List<Student> selectList(String[] ids);
  • 1.

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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

Test

@Test
void selectList() {
    String[] ids = new String[]{"1", "2", "3"};

    List<Student> list = mapper.selectList(ids);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

日志中输出的SQL

select * from tb_student where id in ( ? , ? , ? )
  • 1.

2、List为入参

Mapper

List<Student> selectList(List<String> ids);
  • 1.

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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

Test

@Test
void selectList() {
    List<String> ids = new ArrayList<>();
    ids.add("1");
    ids.add("2");
    ids.add("3");

    List<Student> list = mapper.selectList(ids);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

日志中输出的SQL

select * from tb_student where id in ( ? , ? , ? )
  • 1.

3、Mybatis-plus条件构造器为入参

Mapper

List<Student> selectList(@Param(Constants.WRAPPER) Wrapper<Student> wrapper);
  • 1.

Mapper.xml

<select id="selectList" resultType="com.demo.entity.Student">
    select *
    from tb_student
    ${ew.customSqlSegment}
</select>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

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);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

日志中输出的SQL

select * from tb_student WHERE (id IN (?,?,?))
  • 1.

参考文章

1、 https://mouday.github.io/coding-tree/mybatis-plus/1-MyBatis-Plus.html#自定义-sql 2、Mybatis中使用in()查询