代码自动填充--springboot--项目开发

代码自动填充

引言:

  • 关于代码自动填充,在项目开发当中,有许多重复代码,而使用代码自动填充,可以让我们不去写那么多重复的代码,大大提高写代码的效率,比如,在项目中,新增的时候会有新增时间,新增人,修改的时候有修改时间,修改人,一个一个写,太浪费时间了,每次对数据进行新增、修改和删除都需要对这些字段进行设置。传统的做法是在进行这些操作前,对实体类的字段进行set赋值,然后再进行数据库操作。这种做法的坏处不仅容易忘记导致出错、而且显得代码冗余。

问题分析

  • 创建时间,创建人,修改时间,修改人等字段都属于公共字段,能否将这些公共字段在某个地方统一处理,来简化开发呢?

自定义注解:

  • 首先,定义一个自定义注解

  • @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AutoFill {
        OperationType value();//OperationType类是一个枚举类,里面定义了两个属性,insert和update
    }
    

枚举类

  • 枚举类

  • /**
     * 数据库操作类型
     */
    public enum OperationType {
        /**
         * 更新操作
         */
        UPDATE,
        /**
         * 插入操作
         */
        INSERT
    }
    

切面类

  • 再创建一个切面类,用来实现自动填充

  • /**
     * 自定义切面,实现公共字段自动填充处理逻辑
     */
    @Aspect
    @Component
    @Slf4j
    public class AutoFillAspect {
    
        /**
         * 切入点
         */
        @Pointcut("execution(* com.XXX.mapper.*.*(..)) && @annotation(com.XXX.annotation.AutoFill)")//直接在mapper包中找AutoFill注解,快
        public void autoFillPointCut(){}
    
        /**
         * 前置通知,在通知中进行公共字段的赋值
         */
        @Before("autoFillPointCut()")
        public void autoFill(JoinPoint joinPoint){
            log.info("开始进行公共字段自动填充...");
    
            //获取到当前被拦截的方法上的数据库操作类型
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
            AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
            OperationType operationType = autoFill.value();//获得数据库操作类型
    
            //获取到当前被拦截的方法的参数--实体对象
            Object[] args = joinPoint.getArgs();
            if(args == null || args.length == 0){
                return;
            }
    
            Object entity = args[0];//让实体类都在0号索引,需要开发人员之间约定好,将实体类入参时放在第一个位置
    
            //准备赋值的数据
            LocalDateTime now = LocalDateTime.now();
            Long currentId = BaseContext.getCurrentId();//封装ThreadLocal
    
            //根据当前不同的操作类型,为对应的属性通过反射来赋值
            if(operationType == OperationType.INSERT){
                //为4个公共字段赋值
                try {
                    Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                    Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                    Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                    Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
    
                    //通过反射为对象属性赋值
                    setCreateTime.invoke(entity,now);
                    setCreateUser.invoke(entity,currentId);
                    setUpdateTime.invoke(entity,now);
                    setUpdateUser.invoke(entity,currentId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if(operationType == OperationType.UPDATE){
                //为2个公共字段赋值
                try {
                    Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                    Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
    
                    //通过反射为对象属性赋值
                    setUpdateTime.invoke(entity,now);
                    setUpdateUser.invoke(entity,currentId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    • 注意Object entity = args[0];//让实体类都在0号索引,需要开发人员之间约定好,将实体类入参时放在第一个位置
    • 注意@Pointcut("execution(* com.XXX.mapper.*.*(..)) && @annotation(com.XXX.annotation.AutoFill)")//直接在mapper包中找AutoFill注解,快

使用自定义注解:

  • 在mapper中的更新和插入接口加上我们自定义的注解,@AutoFill

  • @AutoFill(value = OperationType.UPDATE)
    void update(Employee employee);
    
  • 这时,自动填充就做好了
    但是,有一个新的问题,怎样获取修改人的id呢?我这里用的是ThreadLocal,如需了解请转到ThreadLocal文章

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个非常流行的 Java Web 框架,而 MyBatis-Plus 是一个优秀的 ORM 框架,它可以帮助我们更加方便地操作数据库。本篇文章将介绍如何在 Spring Boot 中整合 MyBatis-Plus 3.1。 ## 1. 准备工作 在开始整合之前,我们需要准备好以下环境: - JDK 8+ - Maven 3.2+ - IDE(例如 IntelliJ IDEA 或 Eclipse) ## 2. 创建 Spring Boot 项目 首先,我们需要创建一个 Spring Boot 项目。可以使用 Spring Initializr 来快速创建一个项目。在创建项目的过程中,我们需要选择以下的依赖: - Spring Web - MyBatis-Plus 如果你使用的是 IntelliJ IDEA,可以使用以下方式创建项目: 1. 打开 IntelliJ IDEA,选择 "Create New Project"。 2. 在弹出的对话框中选择 "Spring Initializr"。 3. 配置项目的基本信息,例如 Group、Artifact、Name 等。 4. 在 "Dependencies" 中选择 "Spring Web" 和 "MyBatis-Plus"。 5. 点击 "Next",确认配置信息。 6. 点击 "Finish",完成项目的创建。 如果你使用的是 Eclipse,可以参考以下的步骤: 1. 打开 Eclipse,选择 "File" -> "New" -> "Other"。 2. 在弹出的对话框中选择 "Spring Starter Project"。 3. 配置项目的基本信息,例如 Group、Artifact、Name 等。 4. 在 "Dependencies" 中选择 "Spring Web" 和 "MyBatis-Plus"。 5. 点击 "Finish",完成项目的创建。 ## 3. 配置 MyBatis-Plus 完成项目的创建后,我们需要进行一些配置,以便让 Spring Boot 和 MyBatis-Plus 正常工作。 ### 3.1 配置数据源 首先,我们需要配置数据源。在 Spring Boot 中,我们可以使用以下方式配置数据源: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 这里我们使用的是 MySQL 数据库,你可以根据自己的实际情况进行修改。 2. 在启动类中添加 @EnableTransactionManagement 注解,开启事务管理: ```java @SpringBootApplication @EnableTransactionManagement public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` ### 3.2 配置 MyBatis-Plus 接下来,我们需要配置 MyBatis-Plus。在 Spring Boot 中,我们可以使用以下方式配置 MyBatis-Plus: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml mybatis-plus: mapper-locations: classpath*:mapper/*.xml type-aliases-package: com.example.demo.entity ``` 这里的 mapper-locations 表示 Mapper 文件的位置,type-aliases-package 表示实体类的包路径。 2. 在启动类中添加 @MapperScan 注解,指定 Mapper 文件的包路径: ```java @SpringBootApplication @EnableTransactionManagement @MapperScan("com.example.demo.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` ### 3.3 配置分页插件 MyBatis-Plus 内置了一个分页插件,可以帮助我们更加方便地进行分页查询。 在 Spring Boot 中,我们可以使用以下方式配置分页插件: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml mybatis-plus: configuration: # 分页插件 page-helper: helper-dialect: mysql reasonable: true support-methods-arguments: true params: count=countSql ``` 这里的 helper-dialect 表示数据库类型,reasonable 表示是否启用合理化查询,support-methods-arguments 表示支持多参数查询,params 表示传递给 Mapper 的参数名。 2. 在 Mapper 接口中添加 Page 参数,如下所示: ```java public interface UserMapper extends BaseMapper<User> { List<User> selectUserList(Page<User> page); } ``` ### 3.4 配置自动填充插件 MyBatis-Plus 还内置了一个自动填充插件,可以帮助我们更加方便地进行数据填充。 在 Spring Boot 中,我们可以使用以下方式配置自动填充插件: 1. 在实体类中添加 @TableField 注解,并指定填充策略: ```java @Data public class User { private Long id; private String name; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; } ``` 这里的 fill 表示填充策略,INSERT 表示插入时填充,UPDATE 表示更新时填充。 2. 在 Mapper 接口中添加 @Insert 注解,并指定插入方式: ```java public interface UserMapper extends BaseMapper<User> { @Insert("insert into user(name,create_time,update_time) values(#{name},#{createTime},#{updateTime})") int insertUser(User user); } ``` 这里的 @Insert 注解表示插入数据,#{} 中的属性名与实体类中的属性名一致。 ## 4. 使用 MyBatis-Plus 完成配置后,我们就可以使用 MyBatis-Plus 进行数据库操作了。下面我们来看一些使用示例。 ### 4.1 基本操作 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User selectById(Long id) { return userMapper.selectById(id); } public List<User> selectList() { return userMapper.selectList(null); } public int insert(User user) { return userMapper.insert(user); } public int updateById(User user) { return userMapper.updateById(user); } public int deleteById(Long id) { return userMapper.deleteById(id); } } ``` 这里的 selectById、selectList、insert、updateById、deleteById 分别表示根据 id 查询、查询列表、插入、更新和删除。 ### 4.2 分页查询 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public List<User> selectUserList(int pageNum, int pageSize) { Page<User> page = new Page<>(pageNum, pageSize); return userMapper.selectUserList(page); } } ``` 这里的 selectUserList 表示分页查询,pageNum 表示页码,pageSize 表示每页大小。Page<User> 表示分页对象。 ### 4.3 自动填充 ```java @RestController public class UserController { @Autowired private UserService userService; @PostMapping("/user") public int insert(User user) { return userService.insert(user); } } ``` 这里的 insert 表示插入数据,当插入数据时,createTime 和 updateTime 会自动填充。 ## 5. 总结 本篇文章介绍了如何在 Spring Boot 中整合 MyBatis-Plus 3.1。首先,我们需要创建一个 Spring Boot 项目,并添加相应的依赖。然后,我们需要进行一些配置,包括数据源、MyBatis-Plus、分页插件和自动填充插件。最后,我们使用 MyBatis-Plus 进行数据库操作。 MyBatis-Plus 是一个非常优秀的 ORM 框架,它可以帮助我们更加方便地操作数据库。如果你想提高自己的开发效率,不妨尝试一下 MyBatis-Plus。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值