近期开发中遇到一个主键更新的问题:
需要根据主键更新数据库表有以下两种实现方式:
一、在java中for循环更新(sql直接使用主键)
long start = System.currentTimeMillis();
for(Long id: ids){
drugPatientMapper.updateById(id);
}
long end = System.currentTimeMillis();
log.info("java for循环耗时:{}",end-start);
二、在xml中for循环更新(sql使用foreach更新)
long start = System.currentTimeMillis();
if (ids.size() > 0) {
drugPatientMapper.clearPatientByIds(ids);
}
long end = System.currentTimeMillis();
log.info("xml for循环耗时:{}",end-start);
<update id="clearByIds">
update table set p_no = null
where id in
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
结果:xml耗时162,java耗时244.
结论:所以更新数据库,在数据量小的时候,直接数据库中进行foreach遍历,虽然会有in的作用存在无法使用索引,但是效率还是会更加高一些