mybatis批量操作(批量查询,批量插入,批量更新)
在开发过程中操作大数据量时,连续的循环单个sql操作会导致数据库连接数剧增,整体执行效率也会变的比较低,因此需要使用批量操作,减少连接数,效率更快。
批量查询的方法:
注:如果是简单的批量查询entity,mybatis-plus中有封装好的方法,可以直接使用
复杂一点的:
List<ArticleAccumulatedIncomeDTO> batchAccumulatedIncome(List<Long> ids);
<select resultMap="ArticleSumIncome">
select article_id,sum(income) as accumulated_income
from wallet
<where>
article_id in (
<foreach collection="list" item="id" index="index" separator=",">
#{id}
</foreach>
)
</where>
group by article_id
</select>
批量插入的方法:
int addResource(List<Resource> ResourceList);
<insert parameterType="">
insert into resource (object_id, res_id, res_detail_value, res_detail_name)
values
<foreach collection="list" item=" ResourceList " index="index" separator=",">
( #{,jdbcType=VARCHAR},
#{,jdbcType=VARCHAR},
#{,jdbcType=VARCHAR},
#{,jdbcType=VARCHAR}
)
</foreach>
</insert>
批量更新的方法:
方法一:
int updateRoles(List<String> roleList);
<update parameterType="">
update role
set enabled = '0'
where role_id in
<foreach collection="list" item="roleIds" index="index" open="(" separator="," close=")">
#{roleIds}
</foreach>
</update>
方法二:
void articleBatchUpdate(@Param("list") List<ArticleEntity> list);
<update parameterType="list">
update article
set
base_income =
<foreach collection="list" item="item" index="index"
separator=" " open="case ID" close="end">
when #{} then #{}
</foreach>,
total_income =
<foreach collection="list" item="item" index="index"
separator=" " open="case ID" close="end">
when #{} then #{}
</foreach>,
total_views =
<foreach collection="list" item="item" index="index"
separator=" " open="case ID" close="end">
when #{} then #{}
</foreach>
real_views =
<foreach collection="list" item="item" index="index"
separator=" " open="case ID" close="end">
when #{} then #{}
</foreach>
where id in
<foreach collection="list" index="index" item="item"
separator="," open="(" close=")">
#{}
</foreach>
</update>
================================================================================
控制批量操作方法体:
//批量循环操作方法: objList要操作的数据,maxValue每次批量处理的条数
public void BatchSql(List<Object> objList,int maxValue) {
List<Object> list = new ArrayList<>();
int size = ();
int total = size / maxValue;
if (size % maxValue != 0) {
total += 1;
}
for (int i = 0; i < total; i++) {
if (i == total - 1) {
maxValue = size - (i * maxValue);
}
for (int j = 0; j < maxValue; j++) {
((j));
}
// 批量处理的方法
(list);
("日志:批量xxx。。。");
(list);
();
}
}