要实现按部门的全局数据权限过滤,可以按照以下步骤进行操作:

  1. 添加依赖:在项目的pom.xml文件中添加mybatis-plus的依赖,例如:
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>
  1. 创建数据权限拦截器:创建一个实现Interceptor接口的类,用于拦截数据库查询操作,例如:
public class DataPermissionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取当前登录用户的部门信息
        Department department = getCurrentUserDepartment();
        
        // 获取原始的SQL语句
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
        String originalSql = boundSql.getSql();
        
        // 构建新的SQL语句,加入部门过滤条件
        String newSql = "SELECT * FROM your_table WHERE department_id = " + department.getId() + " AND " + originalSql;
        
        // 替换原始的SQL语句
        Field field = boundSql.getClass().getDeclaredField("sql");
        field.setAccessible(true);
        field.set(boundSql, newSql);
        
        return invocation.proceed();
    }
    
    private Department getCurrentUserDepartment() {
        // 获取当前登录用户的部门信息,可以根据具体的实现进行获取
        // 例如从数据库中查询当前登录用户的部门信息
        // 或者从当前登录用户的token中获取部门信息
        // 返回Department对象
    }
}
  1. 注册数据权限拦截器:在Spring Boot的配置类中注册数据权限拦截器,例如:
@Configuration
public class MybatisPlusConfig {

    @Bean
    public Interceptor dataPermissionInterceptor() {
        return new DataPermissionInterceptor();
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(Interceptor dataPermissionInterceptor) {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(dataPermissionInterceptor);
        return interceptor;
    }
}
  1. 测试数据权限过滤:使用mybatis-plus的查询方法进行测试,例如:
@Autowired
private YourMapper yourMapper;

public List<YourEntity> getDataWithPermission() {
    return yourMapper.selectList(null);
}

在以上代码中,yourMapper是你自己定义的Mapper接口,继承自mybatis-plus的BaseMapper接口。调用selectList方法时,数据权限拦截器会拦截查询操作,并根据当前登录用户的部门信息添加部门过滤条件,返回符合条件的数据。

注意:上述代码中的your_table、Department、YourEntity、YourMapper等是示例,请根据实际情况进行调整

spring boot mybatis-plus 实现按部门的全局数据权限过滤

原文地址: https://www.cveoy.top/t/topic/hyqG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录