MyBatis实现批量修改的三种办法

2年前 (2022) 程序员胖胖胖虎阿
335 0 0

需求:
前端传入List集合对象,实现批量修改。

现实例子:

在用户表中,有字段id,name,classroom,录数据的时候,classroom是空的,只录了id和name信息,现在通过导入id和classroom的excel表格,批量修改学生的classroom值。

思路:

方法一:在service层对List集合进行for循环,每一条记录调用一次MySQL数据库。但是这样对于数据量大的情况下会大大消耗连接数据库的性能。

方法二:在MyBatis的xml文件中使用循环,每条语句用" ;"号隔开,使用事务监控语句执行的情况。但这样会直接报错,因为MyBatis默认不支持批量update语句的,要在连接JDBC的连接信息中加入一下字段:&allowMultiQueries=true。

方法三:使用case函数,将数据同时执行可以解决1的问题,本案例使用这种方法。

case函数语法

update tab_student set
	classroom = case id
		when 1 then "one"
		when 2 then "tow"
		when 3 then "three"
	end
where id in (1,2,3)

解释:

通过id值修改classroom值,
当id=1时classroom=one;
当id=2时classroom=tow;
当id=3时classroom=three;

通常id和classroom都是用循环得出具体值

实体类:

public class Student{
    @ApiModelProperty(name="id",value="id")
    private Long id;
    @ApiModelProperty(name="name",value="名称")
    private String name;
    @ApiModelProperty(name="classroom",value="班级")
    private String classroom;

Mapper层:

Integer importInfo(@Param("students")List<Student> students,@Param("classroom")String classroom);

Mapper.xml文件:

<update id="importInfo">
        update tab_student set
        <foreach collection="students" item="student" open="classroom= case id" close="end,">
            when #{student.id} then #{student.classroom}
        </foreach>
        where id in
        <foreach collection="students" item="student" open="(" close=")" separator=",">
            #{student.id}
        </foreach>
    </update>

用过MyBatis.log查看语句执行情况。

版权声明:程序员胖胖胖虎阿 发表于 2022年9月21日 上午2:32。
转载请注明:MyBatis实现批量修改的三种办法 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...