本来没有想到要优化的,因为用到了mp的分页插件,一开始的目的是返回一个Page对象,但是写完后测试发现无法自动获得记录总条数。并且经人提醒,我的代码在for循环中查询数据库,容易造成安全隐患,于是经过搜索,改良了代码。
代码优化之前:
List<AttrAttrgroupRelation> relationList = .......
List<Long> attrIds = new ArrayList<>();
if(ObjectUtil.isNotEmpty(relation)){
//遍历 relationList ,得到集合 attrIds
attrIds = relationList.stream().map(AttrAttrgroupRelation::getAttrId).collect(Collectors.toList());
}
List<AttrEntity> attrEntities = new ArrayList<>();
//遍历 attrIds ,每次取出一个attrId,从数据库中查询符合条件的实体类,并添加到attrEntities集合中
for (Long attrId : attrIds) {
AttrEntity attrEntity = attrService.getOne(new QueryWrapper<AttrEntity>()
.eq("attr_id", attrId)
.like(StrUtil.isNotBlank(keywords), "attr_name",keywords));
attrEntities.add(attrEntity);
return new Page(pageNum,pageSize).setRecords(attrEntities);
}
代码优化后:
service
List<AttrAttrgroupRelation> relationList = .......
List<Long> attrIds = new ArrayList<>();
if(ObjectUtil.isNotEmpty(relation)){
//遍历 relationList ,得到集合 attrIds
attrIds = relationList.stream().map(AttrAttrgroupRelation::getAttrId).collect(Collectors.toList());
}
Page<AttrEntity> page = new Page<>(pageNum,pageSize);
Page<AttrEntity> attrPage = attrMapper.getAttrEntities(page,attrIds,keywords);
mapper
<select id="getAttrEntities" resultType="xxx.xxx.entity.AttrEntity">
select attr_id,attr_name,search_type,value_type,icon,value_select,attr_type,enable,
catelog_id,show_desc
from pms_attr
where attr_id in
<foreach collection="attrIds" open="(" close=")" separator="," item="attrId">
#{attrId}
</foreach>
<if test="keywords!=null and keywords != ''">
and attr_name like concat('%',#{keywords},'%')
</if>
</select>
总结
- 在我优化后的代码中:
Page<AttrEntity> attrPage = attrMapper.getAttrEntities(page,attrIds,keywords);,page参数看似无意义,其实在MyBatisPlus官网文档中提到了自定义 mapper 的用法,其中最重要的一句话是:如果返回类型是 IPage,则入参的 IPage 不能为 null ,因为返回的 IPage == 入参的 IPage