springBoot + mybatis-plus 实现监听 mysql的数据增删改的监听

在Spring Boot + MyBatis-Plus中实现MySQL数据增删改的监听,可以通过以下步骤:

1. 添加MyBatis-Plus依赖,在pom.xml文件中添加以下依赖:

 

    com.baomidou
    mybatis-plus-boot-starter
    ${mybatis-plus.version}

2. 配置MyBatis-Plus,通常在application.yml文件中进行配置:

mybatis-plus:
  # 数据库类型
  db-type: mysql
  # 实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.example.entity
  # 加载自定义的Mybatis XML映射文件
  mapperLocations: classpath:/mapper/**/*.xml
  # 是否开启SQL打印
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true

3. 创建监听器类,实现com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor接口。 

@Component
public class DataChangeInterceptor implements ISqlParser {

    @Override
    public void parser(MetaObject metaObject) {
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        String sql = mappedStatement.getSqlSource().getBoundSql(metaObject).getSql();
        // 处理SQL语句,检测是否为对指定表进行的增删改操作
        // 如果是,则发送通知给应用程序
    }
}

4. 在MyBatis-Plus配置中添加拦截器。 

@Configuration
public class MybatisPlusConfig {

    @Autowired
    private DataChangeInterceptor dataChangeInterceptor;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(dataChangeInterceptor);
        return interceptor;
    }
}

5. 对需要进行监听操作的实体类添加@TableLogic注解,启用逻辑删除功能。

@Data
@TableName("user")
public class User {

    @TableId(type = IdType.AUTO)
    private Long id;

    private String name;
    
    @TableLogic
    private Integer deleted;
}

以上就是使用Spring Boot + MyBatis-Plus实现MySQL数据增删改的监听的基本步骤。需要注意的是,如果不使用逻辑删除功能,则无法检测到数据删除操作。

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/0c8b29bff7.html