- 个人主页:i笨笨i
- 版权:本文由【i笨笨i】原创,需要转载联系博主
- 欢迎关注、点赞、收藏(一键三连)和订阅专栏哦!
- 一个系列哟
- 瑞吉外卖开发笔记一
- 瑞吉外卖开发笔记二
- 瑞吉外卖开发笔记三
- 瑞吉外卖开发笔记四
- 瑞吉外卖开发笔记五
前边我们已经完成了后台系统的员工管理功能开发,在新增员工时需要创建时间、创建人、修改时间、修改人等字段,在编辑员工时需要设置修改时间和修改人等字段。这些字段属于公共字段,也就是很多表中都有这些字段,如下:
❓能不能对于这些公共字段在某个地方统一处理,来简化开发?
使用MyBatisPlus提供的公共字段自动填充功能
MyBatisPlus公共字段填充,也就是在插入或者更新的时候为指定字段赋予指定的值,使用它的好处就是可以统一对这些字段进行处理,避免了重复代码。
实现步骤:
@TableField
注解,指定自动填充的策略1️⃣在实体类的属性上加入@TableField
注解,指定自动填充的策略
//Employee类的部分属性
@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;
2️⃣按照框架要求编写元数据对象处理器,在此类中统一为公共字段赋值,此类需要实现MetaObjectHandler接口
在设置createUser和updateUser属性时,需要更新人的id,此处无法获取到Session,无法通过Session获取到操作人id。此处暂时由long类型的1代替。
/**
* 自定义元数据对象处理器
*/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 插入操作,自动填充
*
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("createUser", new Long(1));
metaObject.setValue("updateUser", new Long(1));
}
/**
* 更新(修改)操作,自动填充
*
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("updateUser", new Long(1));
}
}
前面我们已经完成了公共字段自动填充功能的代码开发,但是还有一个问题没有解决,就是我们在自动填充createUser和updateUser时设置的用户id是固定值,现在我们需要改造成动态获取当前登录用户的id。
❓用户登录成功后我们将用户id存入了HttpSession中,现在从HttpSession中获取不就行了?
注意,我们在MyMetaObjectHandler中是不能获取HttpSession对象的,所以我们需要从其他方式获取登录用户id。
可以使用ThreadLocal来解决此问题,它是JDK中提供的一个类。
在学习ThreadLocal之前,我们需要先确认一个事情,就是客户端发送的每次http请求,对应的在服务端都会分配一个新的线程来处理,在处理过程中涉及到下面类中的方法都属于同一个线程:
可以在上面的三个方法中分别加入下面代码(获取当前线程id):
long id = Thread.currentThread().getId();
log.info("线程id:{}",id);
执行编辑员工进行验证,通过观察控制台输出可以发现,一次请求对应的线程id是相同的:
❓什么是ThreadLocal?
ThreadLocal并不是一个Thread,而是Thread的局部变量。当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
ThreadLocal为每个线程提供单独一份存储空间,具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外则不能访问。
ThreadLocal常用的方法:
我们可以在LoginCheckFilter的doFilter方法中获取当前登录用户id,并调用ThreadLocal的set方法来设置当前线程的线程局部变量(用户id),然后在MyMetaObjectHandler的updateFill方法中调用ThreadLocal的get方法获得当前线程所对应的线程局部变量的值(用户id)。
实现步骤:
1️⃣编写BaseContext工具类,基于ThreadLocal封装的工具类
/**
* 基于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();
}
}
2️⃣在LoginCheckFilter的doFilter方法中调用BaseContext来设置当前登录用户的id
if (request.getSession().getAttribute("employee") != null) {
Long empId = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
filterChain.doFilter(request, response);
return;
}
3️⃣在MyMetaObjectHandler的方法中调用BaseContext获取登录用户的id
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 插入操作,自动填充
*
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("createUser", BaseContext.getCurrentId());
metaObject.setValue("updateUser", BaseContext.getCurrentId());
}
/**
* 更新(修改)操作,自动填充
*
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("updateUser", BaseContext.getCurrentId());
}
}
后台系统中可以管理分类信息,分类包括两种类型,分别是菜品分类和套餐分类。当我们在后台系统中添加菜品时需要选择一个菜品分类,当我们在后台系统中添加一个套餐时需要选择一个套餐分类,在移动端也会按照菜品分类和套餐分类来展示对应的菜品和套餐。
在开发业务功能前,先将需要用到的类和接口基本结构创建好:
1️⃣实体类Category
/**
* 菜品和套餐分类
* @属性:
* 1、type,类型:1菜品分类,2套餐分类
* 2、name,分类名称
* 3、sort顺序
* 4、createTime,创建时间
* 5、updateTime,更新时间
* 6、createUser,创建人
* 7、updateUser,修改人
* 8、isDeleted,是否删除
*/
@Data
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Integer type;
private String name;
private Integer sort;
@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;
private Integer isDeleted;
}
2️⃣Mapper接口CategoryMapper
@Mapper
public interface CategoryMapper extends BaseMapper<Category> {
}
3️⃣业务层接口及其实现类
public interface CategoryService extends IService<Category> {
}
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
}
4️⃣控制层CategoryController
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
}
在开发代码之前,需要梳理一下整个程序的执行过程:
可以看到新增菜品分类和新增套餐分类请求的服务端地址和提交的json数据相同,所以服务端只需要提供一个方法统一处理即可:
/**
* CategoryController类
* 分类管理
*/
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 新增分类
* @param category
* @return
*/
@PostMapping
public R<String> save(@RequestBody Category category) {
log.info("category:{}", category);
categoryService.save(category);
return R.success("新增分类成功");
}
}
在开发代码之前,需要梳理一下整个程序的执行过程:
注意:要把Category中的private Integer isDeleted;
注释掉才能查询到数据
/**
* 分页查询
* @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);
}
在分类管理列表页面,可以对某个分类进行删除操作。需要注意的是当分类关联了菜品或者套装时,此分类不允许删除。
在开发代码之前,需要梳理一下整个程序的执行过程:
@RequestParam
注解指定获取对应属性。/**
* CategoryController类
* 根据id删除分类
* @param id
* @return
*/
@DeleteMapping
public R<String> delete(@RequestParam(name = "ids") Long id) {
log.info("删除分类,id为:{}", id);
categoryService.removeById(id);
return R.success("分类信息删除成功");
}
前面我们已经实现了根据id删除分类的功能,但是并没有检查删除的分类是否关联了菜品或者套餐,所以需要进行功能完善。
要完善分类删除功能,需要先准备基础的类和接口:
1️⃣实体类Dish和Setmeal
/**
* 菜品
* @属性:
* 1、name,菜品名称
* 2、categoryId菜品分类id
* 3、price,菜品价格
* 4、code商品码
* 5、image,图片
* 6、description,描述信息
* 7、status,0停售,1起售
* 8、sort,顺序
* 9、isDeleted是否删除
*/
@Data
public class Dish implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Long categoryId;
private BigDecimal price;
private String code;
private String image;
private String description;
private Integer status;
private Integer sort;
@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;
private Integer isDeleted;
}
/**
* 套餐
* @属性:
* 1、name,套餐名称
* 2、categoryId,分类id
* 3、price,套餐价格
* 4、code,编码
* 5、image,图片
* 6、description,描述信息
* 7、status,0停用,1起用
* 9、isDeleted是否删除
*/
@Data
public class Setmeal implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Long categoryId;
private String name;
private BigDecimal price;
private Integer status;
private String code;
private String description;
private String image;
@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;
private Integer isDeleted;
}
2️⃣Mapper接口DishMapper和SetmealMapper
@Mapper
public interface DishMapper extends BaseMapper<Dish> {
}
@Mapper
public interface SetmealMapper extends BaseMapper<Setmeal> {
}
3️⃣Service接口DishServicer和SetmealService
public interface DishService extends IService<Dish> {
}
public interface SetmealService extends IService<Setmeal> {
}
4️⃣Service实现类DishServicerImpl和SetmealServiceImpl
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
}
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
}
1️⃣在CategoryService添加remove方法
public interface CategoryService extends IService<Category> {
public void remove(Long id);
}
2️⃣在CategoryServicelmpl实现remove方法
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
@Autowired
private DishService dishService;
@Autowired
private SetmealService setmealService;
/**
* 根据id删除分类,删除之前需要进行判断是否关联了菜品或套餐
* @param id
*/
@Override
public 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<>();
setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
int count2 = setmealService.count(setmealLambdaQueryWrapper);
if (count2 > 0){
//已经关联套餐,抛出一个业务异常
throw new CustomException("当前分类下关联了套餐,不能删除");
}
//正常删除分类
super.removeById(id);
}
}
3️⃣定义异常类CustomException
/**
* 自定义业务异常
* 有在CategoryServiceImpl类的remove方法中抛出
*/
public class CustomException extends RuntimeException {
public CustomException(String message){
super(message);
}
}
4️⃣在全局异常处理器GlobalExceptionHandler类添加
/**
* GlobalExceptionHandler类中
* 处理自定义异常
* 处理异常:CustomException
* @param ex
* @return
*/
@ExceptionHandler(value = CustomException.class)
public R<String> exceptionHandler(CustomException ex){
log.error(ex.getMessage());
return R.error(ex.getMessage());
}
在分类管理列表页面点击修改按钮,弹出修改窗口,在修改窗口回显分类信息
/**
* CategoryController类
* 根据id修改分类信息
* @param category
* @return
*/
@PutMapping
public R<String> update(@RequestBody Category category){
log.info("修改分类信息:{}",category);
categoryService.updateById(category);
return R.success("修改分类信息成功");
}