一般来说进行批量操作的时候都是会想到在service里循环遍历集合,循环调用dao层方法,
例如:
list.stream().forEach(e -> {
double score = 0;
int publishedDay = DateUtils.getDayDiff(new Date(),e.getPublishDate());//获取到已发布天数
int publishDayModulus = (publishedDay - 10) < 0 ? 0 : (publishedDay - 10);
int readBonus = (e.getReadNum()/500)*10;//阅读加成
score = Math.floor(Math.pow(publishDayModulus,3) + readBonus + e.getRecommendWeight() + (e.getBanner() == 0 ? 0 : 1));
e.setScore(score);
newsMapper.batchResetScore(e);
});
逻辑上来说是没有任何问题的,但是在程序执行效率来看却远远大打折扣,所以在这里可以使用mybatis的批量操作,话不多说,直接上代码:
dao层:
void batchResetScore(List<News> list);
xml:
<update id="batchResetScore" parameterType="java.util.List">
update news
set score =
<foreach collection="list" item="item" open="CASE ID" close="end">
when #{item.id} then #{item.score}
</foreach>
where id in
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item.id}
</foreach>
</update>