业务场景
List<StudentEntity> studentEntityList = new ArrayList<StudentEntity>();
// todo: 依据sno批量修改
@Data
@TableName("student")
public class StudentEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.AUTO)
@ExcelProperty("学生id")
private Long id;
@ExcelProperty("学生学号")
private String sno;
@ExcelProperty("头像地址")
private String sportrait;
}
现在,手中存在一个List,每个元素类型是StudentEntity。对于StudentEntity,主键是id。我需要依据sno进行批量修改
问题分析
一开始的想法是:直接调用继承mybatis-plus的service的updateBatchById方法。但这个方法是按照主键id修改,不是sno。因此这个方法走不通。
之后我想遍历list,对其每个元素执行update方法,也就是如下解决方案
studentEntityList.foreach(e -> {
// 设置更新条件
LambdaUpdateWrapper<StudentEntity> wrapper = new LambdaUpdateWrapper<>();
// sno作为修改条件
wrapper.eq(StudentEntity.getSno, e.getSno);
// 设置sportrait
wrapper.set(StudentEntity.getSportrait, e.getSportrait);
this.update(e, wrapper);
})
但这样效率太低,每次update都需要进行数据库连接,关闭。数据量一旦增大,大部分时间都浪费在连接数据库,关闭数据库上。因此,我采用的是自己写sql的方式解决,将所有的update语句在一次数据库的连接关闭中全部执行。
解决方案
如下分别是Mapper中写的方法,xml中编写的sql语句
/**
* 按照sno修改
* @param studentList
*/
void updateImages(@Param("stus") List<StudentEntity> studentList);
<update id="updateImages" parameterType="java.util.List">
<foreach collection="stus" item="item" separator=";">
UPDATE student
SET sportrait = #{item.sportrait}
WHERE
sno = #{item.sno}
</foreach>
</update>
我们使用mybatis-plus的<foreach>标签,将所有的update语句连接在一起,在一次数据库访问中全部更新,以此提高效率。
但这么做的前提是:在数据库连接信息中添加: &allowMultiQueries=true