摘要
- 新需求,之前是填写数字更改排序(行数多,用户体验差);
- 因为在之前的原型图上有涉及到排序的接口,所以在设计表阶段就考虑到添加排序字段“sort_position”(后来也有用到“sort_num”,大差不差,无关紧要);
- 拿到需求,不急着动手,先分析一波:
- 前端传入的应该是一个id数组,后端根据传入数组中id对应的下标来单表更新数据库中的排序字段;
- OK,不难,一个SQL就能解决。
要点
- 确定前端传入的参数类型;
- 判断Dao层该接收什么类型的参数;
- 前端传入id数组;Dao层接收Bean列表。
核心代码
为压缩篇幅,省略了Service层和Dao层的接口,开发过程中一定不能省略,规范编程,从我做起!!!
- Controller层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16/**
* 传入id列表,更新排序信息
* @Param opnMaintenanceParam
* @Param request
* @Param response
* @Return java.lang.Object
* @Author HiF
* @Date 2021/7/5 10:48
*/
public Object editMaintenanceDetailSort( OpnMaintenanceParam opnMaintenanceParam,
HttpServletRequest request,
HttpServletResponse response){
return opnAppServiceI.editMaintenanceDetailSort(opnMaintenanceParam, request, response);
} - Service层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public Object editMaintenanceDetailSort(OpnMaintenanceParam opnMaintenanceParam,
HttpServletRequest request,
HttpServletResponse response) {
List<Long> appIds = opnMaintenanceParam.getAppIds();
if (Validator.isNull(appIds)){
log.warn("参数校验异常!appIds:{}", appIds);
throw new BizException(MessageCodeEnum.NO_UPDATE.getCode(), "参数校验异常!");
}
ArrayList<OpnMaintenanceDto> opnMaintenanceParams = new ArrayList<>();
OpnMaintenanceDto opnMaintenanceDto = null;
for (int i = 0; i < appIds.size(); i++){
opnMaintenanceParam.setId(appIds.get(i));
opnMaintenanceParam.setSortPosition(i + 1);
opnMaintenanceDto = new OpnMaintenanceDto();
BeanUtils.copyProperties(opnMaintenanceParam,opnMaintenanceDto);
opnMaintenanceParams.add(opnMaintenanceDto);
}
return Result.success(opnAppDao.editMaintenanceDetailSort(opnMaintenanceParams));
} - Dao层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<update id="editMaintenanceDetailSort" parameterType="java.util.List">
UPDATE
opn_app
<trim prefix="set" suffixOverrides=",">
<trim prefix="sort_position =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.id!=null">
when id=#{i.id} then #{i.sortPosition}
</if>
</foreach>
</trim>
</trim>
WHERE id IN
<foreach collection="list" item="i" index="index" open="(" separator="," close=")">
#{i.id}
</foreach>
</update>