持续学习&持续更新中…
守破离
一句一句删除的话,会发送很多个请求给MySQL服务器,会对MySQL造成较大的性能影响,也会占用资源和带宽,所以使用批量删除
//TODO 写博客:批量删除
@PostMapping("/attr/relation/delete")
public R batchDeleteRelation(@RequestBody List<AttrAttrGroupRelationVo> relationVos) {
relationService.batchDeleteRelation(relationVos);
return R.ok();
}
@Transactional
@Override
public void batchDeleteRelation(List<AttrAttrGroupRelationVo> relationVos) {
this.baseMapper.batchDeleteRelation(relationVos);
}
@Mapper
public interface AttrAttrgroupRelationDao extends BaseMapper<AttrAttrgroupRelationEntity> {
/*
一句一句删除的话,会发送很多个请求给MySQL服务器,会对MySQL造成较大的性能影响,也会占用资源和带宽,所以使用批量删除
批量删除语句:
DELETE FROM pms_attr_attrgroup_relation
WHERE
('attr_id' = 1 AND 'attr_group_id' = 1)
OR
('attr_id' = 3 AND 'attr_group_id' = 2)
OR ...
*/
void batchDeleteRelation(@Param("relations") List<AttrAttrGroupRelationVo> relationVos);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao">
<!-- 可根据自己的需求,是否要使用 -->
<resultMap type="com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity" id="attrAttrgroupRelationMap">
<result property="id" column="id"/>
<result property="attrId" column="attr_id"/>
<result property="attrGroupId" column="attr_group_id"/>
<result property="attrSort" column="attr_sort"/>
</resultMap>
<delete id="batchDeleteRelation">
DELETE FROM `pms_attr_attrgroup_relation` WHERE
<foreach collection="relations" item="item" separator=" OR ">
(attr_id=#{item.attrId} AND attr_group_id=#{item.attrGroupId})
</foreach>
</delete>
</mapper>
批量添加:
<insert id="batchAddRelation">
INSERT INTO `pms_attr_attrgroup_relation`(attr_id, attr_group_id) VALUES
<foreach collection="relations" item="item" separator=",">
(#{item.attrId} , #{item.attrGroupId})
foreach>
insert>
or
@Transactional
@Override
public void batchAddRelation(List<AttrAttrGroupRelationVo> relationVos) {
// 使用自己写的批量添加也可以
// this.baseMapper.batchAddRelation(relationVos);
List<AttrAttrgroupRelationEntity> collect = relationVos.stream().map(relation -> {
AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
// attrAttrgroupRelationEntity.setAttrId(relation.getAttrId());
// attrAttrgroupRelationEntity.setAttrGroupId(relation.getAttrGroupId());
BeanUtils.copyProperties(relation, attrAttrgroupRelationEntity);
return attrAttrgroupRelationEntity;
}).collect(Collectors.toList());
this.saveBatch(collect);
}
雷丰阳: Java项目《谷粒商城》Java架构师 | 微服务 | 大型电商项目.
本文完,感谢您的关注支持!