基于SpringBoot+Redis的前后端分离外卖项目-苍穹外卖(五)

£神魔★判官ぃ 2024-04-17 10:08 136阅读 0赞

公共字段自动填充

      • 1.1 问题分析
      • 1.2 实现思路
      • 1.3 代码开发
        • 1.3.1 步骤一
        • 1.3.2 步骤二
        • 1.3.3 步骤三
      • 1.4 功能测试

1.1 问题分析

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




































序号 字段名 含义 数据类型
1 create_time 创建时间 datetime
2 create_user 创建人id bigint
3 update_time 修改时间 datetime
4 update_user 修改人id bigint

而针对于这些字段,我们的赋值方式为:

1). 在新增数据时, 将createTime、updateTime 设置为当前时间, createUser、updateUser设置为当前登录用户ID。

2). 在更新数据时, 将updateTime 设置为当前时间, updateUser设置为当前登录用户ID。

在项目中处理这些字段都是在每一个业务方法中进行赋值操作,如下:

新增员工方法:

  1. /**
  2. * 新增员工
  3. *
  4. * @param employeeDTO
  5. */
  6. public void save(EmployeeDTO employeeDTO) {
  7. //.......................
  8. //
  9. //设置当前记录的创建时间和修改时间
  10. employee.setCreateTime(LocalDateTime.now());
  11. employee.setUpdateTime(LocalDateTime.now());
  12. //设置当前记录创建人id和修改人id
  13. employee.setCreateUser(BaseContext.getCurrentId());//目前写个假数据,后期修改
  14. employee.setUpdateUser(BaseContext.getCurrentId());
  15. ///
  16. employeeMapper.insert(employee);
  17. }

编辑员工方法:

  1. /**
  2. * 编辑员工信息
  3. *
  4. * @param employeeDTO
  5. */
  6. public void update(EmployeeDTO employeeDTO) {
  7. //........................................
  8. ///
  9. employee.setUpdateTime(LocalDateTime.now());
  10. employee.setUpdateUser(BaseContext.getCurrentId());
  11. ///
  12. employeeMapper.update(employee);
  13. }

新增菜品分类方法:

  1. /**
  2. * 新增分类
  3. * @param categoryDTO
  4. */
  5. public void save(CategoryDTO categoryDTO) {
  6. //....................................
  7. //
  8. //设置创建时间、修改时间、创建人、修改人
  9. category.setCreateTime(LocalDateTime.now());
  10. category.setUpdateTime(LocalDateTime.now());
  11. category.setCreateUser(BaseContext.getCurrentId());
  12. category.setUpdateUser(BaseContext.getCurrentId());
  13. ///
  14. categoryMapper.insert(category);
  15. }

修改菜品分类方法:

  1. /**
  2. * 修改分类
  3. * @param categoryDTO
  4. */
  5. public void update(CategoryDTO categoryDTO) {
  6. //....................................
  7. //
  8. //设置修改时间、修改人
  9. category.setUpdateTime(LocalDateTime.now());
  10. category.setUpdateUser(BaseContext.getCurrentId());
  11. //
  12. categoryMapper.update(category);
  13. }

如果都按照上述的操作方式来处理这些公共字段, 需要在每一个业务方法中进行操作, 编码相对冗余、繁琐,那能不能对于这些公共字段在某个地方统一处理,来简化开发呢?

答案是可以的,我们使用AOP切面编程,实现功能增强,来完成公共字段自动填充功能。

1.2 实现思路

在实现公共字段自动填充,也就是在插入或者更新的时候为指定字段赋予指定的值,使用它的好处就是可以统一对这些字段进行处理,避免了重复代码。在上述的问题分析中,我们提到有四个公共字段,需要在新增/更新中进行赋值操作, 具体情况如下:









































序号 字段名 含义 数据类型 操作类型
1 create_time 创建时间 datetime insert
2 create_user 创建人id bigint insert
3 update_time 修改时间 datetime insert、update
4 update_user 修改人id bigint insert、update

实现步骤:

1). 自定义注解 AutoFill,用于标识需要进行公共字段自动填充的方法

2). 自定义切面类 AutoFillAspect,统一拦截加入了 AutoFill 注解的方法,通过反射为公共字段赋值

3). 在 Mapper 的方法上加入 AutoFill 注解

若要实现上述步骤,需掌握以下知识

技术点:枚举、注解、AOP、反射

1.3 代码开发

1.3.1 步骤一

自定义注解 AutoFill

进入到sky-server模块,创建com.sky.annotation包。

  1. package com.sky.annotation;
  2. /**
  3. * 自定义注解,用于标识某个方法需要进行功能字段自动填充处理
  4. */
  5. @Target(ElementType.METHOD)
  6. @Retention(RetentionPolicy.RUNTIME)
  7. public @interface AutoFill {
  8. //数据库操作类型:UPDATE INSERT
  9. OperationType value();
  10. }

其中OperationType已在sky-common模块中定义

  1. package com.sky.enumeration;
  2. /**
  3. * 数据库操作类型
  4. */
  5. public enum OperationType {
  6. /**
  7. * 更新操作
  8. */
  9. UPDATE,
  10. /**
  11. * 插入操作
  12. */
  13. INSERT
  14. }
1.3.2 步骤二

自定义切面 AutoFillAspect

在sky-server模块,创建com.sky.aspect包。

  1. package com.sky.aspect;
  2. /**
  3. * 自定义切面,实现公共字段自动填充处理逻辑
  4. */
  5. @Aspect
  6. @Component
  7. @Slf4j
  8. public class AutoFillAspect {
  9. /**
  10. * 切入点
  11. */
  12. @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
  13. public void autoFillPointCut(){
  14. }
  15. /**
  16. * 前置通知,在通知中进行公共字段的赋值
  17. */
  18. @Before("autoFillPointCut()")
  19. public void autoFill(JoinPoint joinPoint){
  20. /重要
  21. //可先进行调试,是否能进入该方法 提前在mapper方法添加AutoFill注解
  22. log.info("开始进行公共字段自动填充...");
  23. }
  24. }

完善自定义切面 AutoFillAspect 的 autoFill 方法

  1. package com.sky.aspect;
  2. import .......
  3. /**
  4. * 自定义切面,实现公共字段自动填充处理逻辑
  5. */
  6. @Aspect
  7. @Component
  8. @Slf4j
  9. public class AutoFillAspect {
  10. /**
  11. * 切入点
  12. */
  13. @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
  14. public void autoFillPointCut(){
  15. }
  16. /**
  17. * 前置通知,在通知中进行公共字段的赋值
  18. */
  19. @Before("autoFillPointCut()")
  20. public void autoFill(JoinPoint joinPoint){
  21. log.info("开始进行公共字段自动填充...");
  22. //获取到当前被拦截的方法上的数据库操作类型
  23. MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
  24. AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
  25. OperationType operationType = autoFill.value();//获得数据库操作类型
  26. //获取到当前被拦截的方法的参数--实体对象
  27. Object[] args = joinPoint.getArgs();
  28. if(args == null || args.length == 0){
  29. return;
  30. }
  31. Object entity = args[0];
  32. //准备赋值的数据
  33. LocalDateTime now = LocalDateTime.now();
  34. Long currentId = BaseContext.getCurrentId();
  35. //根据当前不同的操作类型,为对应的属性通过反射来赋值
  36. if(operationType == OperationType.INSERT){
  37. //为4个公共字段赋值
  38. try {
  39. Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
  40. Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
  41. Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
  42. Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
  43. //通过反射为对象属性赋值
  44. setCreateTime.invoke(entity,now);
  45. setCreateUser.invoke(entity,currentId);
  46. setUpdateTime.invoke(entity,now);
  47. setUpdateUser.invoke(entity,currentId);
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. }else if(operationType == OperationType.UPDATE){
  52. //为2个公共字段赋值
  53. try {
  54. Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
  55. Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
  56. //通过反射为对象属性赋值
  57. setUpdateTime.invoke(entity,now);
  58. setUpdateUser.invoke(entity,currentId);
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. }
  64. }
1.3.3 步骤三

在Mapper接口的方法上加入 AutoFill 注解

CategoryMapper为例,分别在新增和修改方法添加@AutoFill()注解,也需要EmployeeMapper做相同操作

  1. package com.sky.mapper;
  2. @Mapper
  3. public interface CategoryMapper {
  4. /**
  5. * 插入数据
  6. * @param category
  7. */
  8. @Insert("insert into category(type, name, sort, status, create_time, update_time, create_user, update_user)" +
  9. " VALUES" +
  10. " (#{type}, #{name}, #{sort}, #{status}, #{createTime}, #{updateTime}, #{createUser}, #{updateUser})")
  11. @AutoFill(value = OperationType.INSERT)
  12. void insert(Category category);
  13. /**
  14. * 根据id修改分类
  15. * @param category
  16. */
  17. @AutoFill(value = OperationType.UPDATE)
  18. void update(Category category);
  19. }

同时,将业务层为公共字段赋值的代码注释掉。

1). 将员工管理的新增和编辑方法中的公共字段赋值的代码注释。

2). 将菜品分类管理的新增和修改方法中的公共字段赋值的代码注释。

1.4 功能测试

新增菜品分类为例,进行测试

启动项目和Nginx

在这里插入图片描述

查看控制台

通过观察控制台输出的SQL来确定公共字段填充是否完成
在这里插入图片描述

查看表

category表中数据
在这里插入图片描述

其中create_time,update_time,create_user,update_user字段都已完成自动填充。

由于使用admin(id=1)用户登录进行菜品添加操作,故create_user,update_user都为1.

后记
????美好的一天,到此结束,下次继续努力!欲知后续,请看下回分解,写作不易,感谢大家的支持!! ???

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读