mybatis动态SQL-<foreach>标签实现批量新增

  • Post author:
  • Post category:其他


在mybatis中,有时我们需要批量插入和更新MySQL中的数据,这时我们就可以使用mybatis中为我们提供的<foreach>标签了,下面看看该怎么使用<foreach>标签去实现批量插入。

注:案例代码参照《

SpringBoot整MyBatis

》中的代码。



<foreach>标签实现批量插入:




在SysUserMapper.xml中增加id=”batchInsert”的<insert>映射:

<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id">
        insert into sys_user (user_name, user_code, user_info, status) values
        <foreach collection="sysUserList" item="user" separator=",">
            (#{user.userName}, #{user.userCode}, #{user.userInfo}, #{user.status})
        </foreach>
    </insert>



SysUserMapper.java新增方法:

/**
     * @Description 批量新增
     * @Author chengjunyu
     * @Date 2022/1/24 22:50
     * @Param sysUserList
     * @Return int
     * @Exception
     */
    int batchInsert(List<SysUser> sysUserList);



SysUserService.java新增方法:

/**
     * @param sysUserList
     * @Description 批量新增
     * @Author chengjunyu
     * @Date 2022/1/24 22:50
     * @Param sysUserList
     * @Return int
     * @Exception
     */
    @Override
    public int batchInsert(List<SysUser> sysUserList) {
        return sysUserMapper.batchInsert(sysUserList);
    }



SysUserController.java新增方法:

@PostMapping("/batchInsert")
    public String batchInsert() {
        List<SysUser> sysUserList = new ArrayList<>();
        for(int i = 0; i < 5; i++) {
            SysUser sysUser = new SysUser();
            sysUser.setUserName("testBatch" + i);
            sysUser.setUserCode("testBatch" + i);
            sysUser.setUserInfo("这是第" + i + "条测试批量新增信息");
            sysUser.setStatus("0");
            sysUserList.add(sysUser);
        }
        int count = sysUserService.batchInsert(sysUserList);
        if(count > 0) {
            System.out.println("成功批量新增信息" + count + "条");
            return "成功批量新增信息" + count + "条";
        }
        return "批量新增失败";
    }



PostMan测试查询结果:



控制台日志信息:



版权声明:本文为threelifeadv原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。