Mybatis的批量查询,批量更新

时间:2025-03-20 13:14:23

批量查询操作

0. 前言

忽略controller、service、repository等逻辑层代码。

1. mapper层定义查询方法

注@Param参数是绑定xml里面的collection参数

List<TestDTO> queryByIds(@Param("idList") List<Long> idList);

2. xml文件中写SQL语句

<select id="queryByIds" resultType="TestDTO">
   select * from test_table
   <where>
      <if test="idList != null and () > 0">
         id in
        <foreach collection="idList" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
      </if>
  </where>
</select>

批量更新操作

0. 前言

假设项目已经连接好数据库,定义好了实体类 且实体类名为MybatisDTO;

id 主键
address 地址

实现需求为通过id批量更新地址信息。

Class MybatisDTO{
    Integer id;
    String address;
}

1. Controller层

@ApiOperation("批量更新")
@PutMapping(value = "/batchUpdate")
public ResponseEntity batchUpdate(@PathVariable("organizationId") Long tenantId,
                                  String defaultAddress,
                                  @RequestBody List<MybatisDTO> mybatisDTOS){
        mybatisService.batchUpdate(mybatisDTOS,defaultAddress);
        return ResponseEntity.ok(HttpStatus.OK);
    }

2. service层

public interface BatchUpdateService{
    void batchUpdate(List<MybatisDTO> mybatisDTOS, String defaultAddress);
}

public class BatchUpdateServiceImpl extends BatchUpdateService{
    @Autowird
    private BatchUpdateMapper batchUpdateMapper;
    public void batchUpdate(List<MybatisDTOS> mybatisDTOS,String defaultAddress){
        batchUpdateMapper.batchUpdate(mybatisDTOS,defaultAddress);
    }
}

3. mapper层

public interface BatchUpdateMapper{
    void batchUpdate(List<MybatisDTO> mybatisDTOS,String defaultAddress);
}

4. XML文件

    <update id="batchUpdate" parameterType="">
        update hcbm_sign_archive
        <trim prefix="set archive_address =">
        <if test="defaultAddress !=null and defaultAddress !=''">
                #{defaultAddress}
        </if>
        <if test="defaultAddress == null">
        <trim prefix="(case id" suffix="end)">
            <foreach collection="MybatisDTOS" item="a" index="index">
                when #{a.id} then #{a.archiveAddress}
            </foreach>
        </trim>
        </if>
        </trim>
        where
        <foreach collection="MybatisDTOs" separator="or" item="a" index="index">
            id=#{a.id}
        </foreach>
    </update>
//这种方式一直报错 未解决
<!--        <foreach collection="MybatisDTOs" item="item" index="index">-->
<!--            set archive_address = #{item.archiveAddress}-->
<!--            where id = #{item.id};-->
<!--        </foreach>-->