您的位置 首页 java

MyBatis批量添加、更新、删除实战篇(日常开发必看)

前言

工作中,经常会遇到很多批量操作的需求:批量添加、批量更新、批量删除、批量导入、批量审核等等,下面这篇文章我们将一一复现,首先我们先了解一下mybatis的标签 foreach 循环:

一、MybatIs标签foreach

foreach元素的属性主要有 item,index,collection,open,separator, close

1》item集合中每一个元素进行迭代时的别名

2》index表示在迭代过程中,每次迭代到的位置

3》open该语句以什么开始

4》separator在每次进行迭代之间以什么符号作为分隔符

5》close以什么结束

1. collection 属性主要有一下3种情况:

1.1 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

1.2 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

1.3 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了

二、批量添加

当传入参数是list集合的时候:

2.1 Mapper.xml

 <!--批量插入员工数据-->
<insert id="saveEmp" parameterType="java.util.List">
    INSERT INTO t_employee(id, name, age, salary, department_id,update_time)
    VALUES
    <foreach collection="list" item="item" index="index" separator=",">
        (#{item.id},#{item.name},#{item.age},#{item.salary},#{item.departmentId},now())
    </foreach>
</insert>  

2.2 Controller层

 @PostMapping("saveBath")
@ResponseBody
public CommonResult<Employee> saveBath(@RequestBody List<Employee> employeeList){
    return employeeService.saveEmp(employeeList);
}  

@ResponseBody:返回 Json 数据 @RequestBody:接受Json数据

2.3 Json数组集合数据

 [
    {
    "id": 1,
    "name": "DT测试1",
    "age": 26,
    "salary": 10000.0,
    "departmentId": 1
    },
    {
    "id": 2,
    "name": "DT测试2",
    "age": 26,
    "salary": 10000.0,
    "departmentId": 2
    }
]  

三、批量更新

1.Mapper.xml

1.1 批量更新第一种方法

 <update id="updateBatch" parameterType="java.util.List" >
    <foreach collection="list" item="item" index="index" separator=";">
        UPDATE t_employee
        <set>
            <if test="item.name != null and item.name != ''" >
                name = #{item.name},
            </if>
            <if test="item.age != null" >
                age = #{item.age},
            </if>
            <if test="item.salary != null" >
                salary = #{item.salary},
            </if>
            <if test="item.salary != null" >
                salary = #{item.departmentId},
            </if>
        </set>
        where id = #{item.id}
    </foreach>
</update>  

记得连接数据库加:

 allowMultiQueries=true  

不然会报如下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘UPDATE t_employee

MySQL 连接数据库时,添加语句:“allowMultiQueries=true”的作用:

1.可以在sql语句后携带 分号 ,实现多语句执行。 2.可以执行批处理,同时发出多个 SQL语句

这种方式就是通过SQL拼接,单条单条地进行更新。

1.2 批量更新第二种方法

 <update id="updateBatch" parameterType="java.util.List" >
    update t_employee
    < trim  prefix="set" suffixOverrides=",">
        <trim prefix="name=case" suffix="end,">
            <foreach collection="list" item="i" index="index">
                <if test="i.name != null and i.name != ''">
                    when id=#{i.id} then #{i.name}
                </if>
            </foreach>
        </trim>
        <trim prefix="age=case" suffix="end,">
            <foreach collection="list" item="i" index="index">
                <if test="i.age != null">
                    when id=#{i.id} then #{i.age}
                </if>
            </foreach>
        </trim>
    </trim>
    where
    <foreach collection="list" separator="or" item="i" index="index" >
        id = #{i.id}
    </foreach>
</update>  

实际上是通过case when语句进行批量更新,只要一条 SQL 语句:

当然除了上面两种方式外,还可通过如下:

 批量更新第三种方法,用ON DUPLICATE KEY UPDATE,就是一个批量插入操作,在插入的时候,如果已存在,则更新,所以可以变相达到批量修改的效果。  

一般不推荐这种更新大数据量的SQL,关于这种方式小编前面的文章也有说过使用方式,这里不再赘述。

注意:上面的方式是针对多个字段的情况,如果只是更新单个字段,可以这么写:

 <!-- 批量更新第二种方法,针对单个字段进行批量更新 -->
<update id="updateBatch" parameterType="java.util.List">
    UPDATE t_employee
    SET name = CASE
    <foreach collection="list" item="item" index="index">
        WHEN id = #{item.id} THEN #{item.name}
    </foreach>
    END
    WHERE id IN
    <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{item.id}
    </foreach>
</update>  

2.Controller层

  @PostMapping("updateBatch")
 @ResponseBody
 public CommonResult<Employee> updateBatch(@RequestBody List<Employee> employeeList){
     return employeeService.updateBatch(employeeList);
 }  

3.Json集合数据

 [
    {
    "id": 1,
    "name": "DT测试111",
    "age": 2611
    },
    {
    "id": 2,
    "name": "DT测试211",
    "age": 2611
    }
]  

四、批量删除

1. 传入的是List数组对象

1.Mapper.xml

 <delete id="deleteBath" parameterType="java.util.List">
   DELETE FROM t_employee WHERE id IN
    <foreach collection="list" item="item" open="(" separator="," close=")">
        #{item.id}
    </foreach>
</delete>  

2.Controller层

 @PostMapping("deleteBath")
@ResponseBody
 public CommonResult<Employee> deleteBath(@RequestBody List<Employee> employeeList){
     return employeeService.deleteBath(employeeList);
 }  

3.Json集合数据

 [
    {
    "id": 1
    },
    {
    "id": 2
    }
]  

2. 传入的是数组

1.Mapper.xml

 <delete id="deleteBath" parameterType="java.util.Arrays">
    DELETE FROM t_employee WHERE id IN
    <foreach collection="array" item="ids" open="(" separator="," close=")">
        #{ids}
    </foreach>
</delete>  

2.Controller层

 @PostMapping("deleteBath")
@ResponseBody
public CommonResult<Employee> deleteBath(@RequestBody int[] ids){
    return employeeService.deleteBath(ids);
}  

3.Json数组

 [1,2]  

2. 传入的是Map集合

1.Mapper.xml

 <delete id="deleteBath" parameterType="java.util.Map">
    DELETE FROM t_employee WHERE id IN
    <foreach collection="ids" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</delete>  
 int deleteBath(@Param("ids") Map<String, Integer> ids);  

2.Controller层

  @PostMapping("deleteBath")
 @ResponseBody
 public CommonResult<Employee> deleteBath(@RequestBody Map<String,Object> map){
     // 接收List
     List<Integer> ids = (List<Integer>) map.get("ids");
     Map<String, Integer> stringMap = new HashMap<>();
     ids.forEach(id -> stringMap.put("ids", id));
     return employeeService.deleteBath(stringMap);
 }  

3.map数据

 {
    "ids": [1,2]
}  

五、批量查询

1.Mapper.xml

 <select id="findBath" resultType="com.dt.springbootdemo.entity.Employee" parameterType="com.dt.springbootdemo.entity.Employee">
    SELECT * FROM t_employee WHERE id IN
    <foreach collection="list" item="item" open="(" separator="," close=")">
        #{item.id}
    </foreach>
</select>  

2.Controller层

 @GetMapping("findBath")
@ResponseBody
public CommonResult<List<Employee>> findBath(@RequestBody List<Employee> employeeList){
    return employeeService.findBath(employeeList);
}  

3.Json集合数据

 [
    {
    "id": 1
    },
    {
    "id": 2
    }
]  

至于其它的数据格式就不再赘述了,很简单,变一下数据格式就可以了:

文章来源:智云一二三科技

文章标题:MyBatis批量添加、更新、删除实战篇(日常开发必看)

文章地址:https://www.zhihuclub.com/195581.shtml

关于作者: 智云科技

热门文章

网站地图