现实例子:
在用户表中,有字段id,name,classroom,录数据的时候,classroom是空的,只录了id和name信息,现在通过导入id和classroom的excel表格,批量修改学生的classroom值。
思路:
方法一:在service层对List集合进行for循环,每一条记录调用一次MySQL数据库。但是这样对于数据量大的情况下会大大消耗连接数据库的性能。
方法二:在MyBatis的xml文件中使用循环,每条语句用" ;"号隔开,使用事务监控语句执行的情况。但这样会直接报错,因为MyBatis默认不支持批量update语句的,要在连接JDBC的连接信息中加入一下字段:&allowMultiQueries=true。
方法三:使用case函数,将数据同时执行可以解决1的问题,本案例使用这种方法。
case函数语法
1.修改一个参数:
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)
讯享网
2.修改多个参数:
讯享网update tab_student set classroom = case id when 1 then "classroom1" when 2 then "classroom2" when 3 then "classroom3" end, name = case id when 1 then "name1" when 2 then "name2" when 3 then "name3" 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查看语句执行情况。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/97248.html