公共字段自动填充功能

问题分析
前面已经完成了后台系统的员工管理功能开发,在新增员工时需要设置创建时间、创建人、修改时间、修改人等字段,在编辑员工时需要设置修改时间和修改人等字段。这些字段属于公共字段,也就是很多表中都有这些字段,如下:


能不能对于这些公共字段在某个地方统一处理,来简化开发?
答案就是使用Mybatis Plus提供的公共字段自动填充功能。Mybatis Plus的公共字段自动填充,也就是在插入或者更新的时候为指定字段赋予指定的值,使用它的好处就是可以统一对这些字段进行处理,避免了重复代码。

代码实现

实现步骤:

  1. 在实体类的属性上加入@Tablefield注解,指定自动填充的策略
//插入时填充字段@TableField(fill = FieldFill.INSERT)private LocalDateTime createTime;//插入和更新是填充字段@TableField(fill = FieldFill.INSERT_UPDATE)private LocalDateTime updateTime;//插入时填充字段@TableField(fill = FieldFill.INSERT)private Long createUser;//插入和更新是填充字段@TableField(fill = FieldFill.INSERT_UPDATE)private Long updateUser;
  1. 按照Mybatis Plus框架要求编写元数据对象处理器,在此类中统一为公共字段赋值,此类需要实现MetaObjectHandler接口。注意:当前设置createUser和updateUser为固定值,后面需要再完善,改为动态获取当前登录用户的id。
  2. 在自动填充 createUser和updateUser时设置的用户id是固定值,现在需要改造成动态获取当前登录用户的id。用户登录成功后我们将用户id存入了 Httpsession中,现在从 Httpsession中获取不就行了?注意,在 MyMetaObjectHandler类中是不能获得 Httpsession对象的,所以需要通过其他方式来获取登录用户id。可以使用 Threadlocal来解决此问题,它是JDK中提供的一个类。

    执行编辑员工功能进行验证,通过观察控制台输出可以发现,一次请求对应的线程id是相同的:

    功能完善


实现步骤:

  1. 编写 BaseContext工具类,基于 Threadloca封装的工具类
  2. 在 LoginCheckFilter的doFilter方法中调用BaseContext来设置当前登录用户的id
  3. 在 MyMetaObjectHandler的方法中调用BaseContext获取登录用户的id
package com.itheima.reggie.common;/** * 基于ThreadLocal封装工具类,用户保存和获取当前登录用户id */public class BaseContext {private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();/** * 设置值 * @param id */public static void setCurrentId(Long id){threadLocal.set(id);}/** * 获取值 * @return */public static Long getCurrentId(){return threadLocal.get();}}
package com.itheima.reggie.common;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.reflection.MetaObject;import org.springframework.stereotype.Component;import java.time.LocalDateTime;/** * 自定义元数据对象处理器 */@Component@Slf4jpublic class MyMetaObjectHandler implements MetaObjectHandler {/** * 插入操作,自动填充 * @param metaObject */@Overridepublic void insertFill(MetaObject metaObject) {log.info("公共字段自动填充[insert]...");log.info(metaObject.toString());metaObject.setValue("createTime", LocalDateTime.now());metaObject.setValue("updateTime",LocalDateTime.now());metaObject.setValue("createUser",BaseContext.getCurrentId());metaObject.setValue("updateUser",BaseContext.getCurrentId());}/** * 更新操作,自动填充 * @param metaObject */@Overridepublic void updateFill(MetaObject metaObject) {log.info("公共字段自动填充[update]...");log.info(metaObject.toString());long id = Thread.currentThread().getId();log.info("线程id为:{}",id);metaObject.setValue("updateTime",LocalDateTime.now());metaObject.setValue("updateUser",BaseContext.getCurrentId());}}

新增分类功能

需求分析
后台系统中可以管理分类信息,分类包括两种类型,分别是菜品分类和套餐分类。当我们在后台系统中添加菜品时需要选择一个菜品分类,当我们在后台系统中添加一个套餐时需要选择一个套餐分类,在移动端也会按照菜品分类和套餐分类来展示对应的菜品和套餐。

可以在后台系统的分类管理页面分别添加菜品分类和套餐分类,如下:

数据模型
新增分类,其实就是将我们新增窗口录入的分类数据插入到 category表,表结构如下:

需要注意,category表中对name字段加入了唯一约束,保证分类的名称是唯一的:

代码开发

在开发业务功能前,先将需要用到的类和接口基本结构创建好:

  1. 实体类 Category
  2. Mapper接口CategoryMapper
  3. 业务层接口CategoryService
  4. 业务层实现类CategoryServicelmpl
  5. 控制层 CategoryController

在开发代码之前,需要梳理一下整个程序的执行过程:

  1. 页面( backend/page/category/list.html发送ajax请求,将新增分类窗口输入的数据以json形式提交到服务端
  2. 服务端Controller接收页面提交的数据并调用Service将数据进行保存
  3. Service调用Mapper操作数据库,保存数据

可以看到新增菜品分类和新增套餐分类请求的服务端地址和提交的json数据结构相同,所以服务端只需要提供一个方法统处理即可

package com.itheima.reggie.controller;import com.itheima.reggie.common.R;import com.itheima.reggie.entity.Category;import com.itheima.reggie.service.CategoryService;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * 分类管理 */@RestController@RequestMapping("/category")@Slf4jpublic class CategoryController {@Autowiredprivate CategoryService categoryService;/** * 新增分类 * @param category * @return */@PostMappingpublic R<String> save(@RequestBody Category category){log.info("category:{}", category);categoryService.save(category);return R.success("新增分类成功");}}

分类信息分页查询功能

需求分析

代码实现
在开发代码之前,需要梳理一下整个程序的执行过程:

  1. 页面发送ajax请求,将分页查询参数(page、 pagesize、name)提交到服务端
  2. 服务端Controller接收页面提交的数据并调用Service查询数据
  3. Service调用 Mapper操作数据库,查询分页数据
  4. Controller将查询到的分页数据响应给页面
  5. 页面接收到分页数据井通过ElementUI的Table组件展示到页面上

/** * 分页查询 * @param page * @param pageSize * @return */@GetMapping("/page")public R<Page> page(int page, int pageSize){//分页构造器Page<Category> pageInfo = new Page<>(page,pageSize);//条件构造器LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();//添加排序条件,根据sort进行排序queryWrapper.orderByAsc(Category::getSort);//分页查询categoryService.page(pageInfo,queryWrapper);return R.success(pageInfo);}

删除分类功能

需求分析
在分类管理列表页面,可以对某个分类进行删除操作。需要注意的是当分类关联了菜品或者套餐时,此分类不允许删除。

代码实现

在开发代码之前,需要梳理一下整个程序的执行过程:

  1. 页面发送ajax请求,将参数(id)提交到服务端
  2. 服务端Controller接收页面提交的数据并调用Service删除数据
  3. Service调用 Mapper操作数据库

/** * 根据id删除分类 * @param id * @return */@DeleteMappingpublic R<String> delete(Long id){log.info("删除分类, id为:{}", id);categoryService.removeById(id);return R.success("分类信息删除成功");}

功能完善

前面已经实现了根据id删除分类的功能,但是并没有检查删除的分类是否关联了菜品或者套餐,所以我们需要进行功能完善。要完善分类删除功能,需要先准备基础的类和接口:
1、实体类Dish和Setmea
2、Mapper接口DishMapper和SetmealMapper
3、Service接口DishService和SetmealService
4、Service实现类 Dishservicelmpl和 Setmealservicelmpl

/** * 根据id删除分类 * @param id * @return */@DeleteMappingpublic R<String> delete(@RequestParam("ids") Long id){log.info("删除分类, id为:{}", id);//categoryService.removeById(id);categoryService.remove(id);return R.success("分类信息删除成功");}
package com.itheima.reggie.service.impl;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.itheima.reggie.common.CustomException;import com.itheima.reggie.entity.Category;import com.itheima.reggie.entity.Dish;import com.itheima.reggie.entity.Setmeal;import com.itheima.reggie.mapper.CategoryMapper;import com.itheima.reggie.service.CategoryService;import com.itheima.reggie.service.DishService;import com.itheima.reggie.service.SetmealService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {@Autowiredprivate DishService dishService;@Autowiredprivate SetmealService setmealService;/** * 根据id删除分类,删除之前需要进行判断 * @param id */@Overridepublic void remove(Long id) {LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();//添加查询条件,根据分类id进行查询dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);int count1 = dishService.count(dishLambdaQueryWrapper);//查询当前分类是否关联了菜品,如果已经关联,抛出一个异常if(count1 > 0){//已经关联菜品,抛出一个业务异常throw new CustomException("当前分类下关联了菜品,不能删除");}//查询当前分类是否关联了套餐,如果已经关联,抛出一个业务异常LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();//添加查询条件,根据分类id进行查询setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);int count2 = setmealService.count(setmealLambdaQueryWrapper);if(count2 > 0){//已经关联套餐,抛出一个业务异常throw new CustomException("当前分类下关联了套餐,不能删除");}//正常删除分类super.removeById(id);}}

修改分类功能

需求分析

在分类管理列表页面点击修改按钮,弹出修改窗口,在修改窗口回显分类信息并进行修改,最后点击确定按钮完成修改操作

代码实现

/** * 根据id修改分类信息 * @param category * @return */@PutMappingpublic R<String> update(@RequestBody Category category){log.info("修改分类信息:{}",category);categoryService.updateById(category);return R.success("修改分类信息成功");}