本文将结合实例代码,介绍Springboot+mybatis-plus+注解实现数据权限隔离,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
1.创建注解
当此注解打在类上,不需要传参,该类下所有查询接口开启数据隔离;打在方法上默认开启数据隔离,传参为false则该方法关闭验证
/** * 数据权限验证注解 * @author xiaohua * @date 2021/6/23 */ @Documented @Target({METHOD, ANNOTATION_TYPE, TYPE}) @Retention(RUNTIME) public @interface DataPermission { /** * 是否要进行数据权限隔离 */ boolean isPermi() default true; }
2. 具体实现
@Component @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) public class DataPermissionInterceptor implements Interceptor { private static final Logger logger = LoggerFactory.getLogger(DataPermissionInterceptor.class); @Autowired private TokenService tokenService; //扫描的包路径(根据自己的项目路径来),这里是取的配置里的包路径 @Value("${permission.package-path}") private String packagePath; private final static String DEPT_ID = "dept_id"; private final static String USER_ID = "create_user"; private static List classNames; @Override public Object intercept(Invocation invocation) throws Throwable { try { LoginInfo user = tokenService.getLoginInfo(); if (user == null){ return invocation.proceed(); } List deptIds = (List) Convert.toList(user.getDataScope()); if (deptIds == null){ deptIds = new ArrayList(); } //反射扫包会比较慢,这里做了个懒加载 if (classNames == null) { synchronized (LazyInit.class){ if (classNames == null){ //扫描指定包路径下所有包含指定注解的类 Set deptIds,Long userId) { try { String condition = ""; String permissionSql = "("; if (deptIds.size() > 0){ for (Long deptId : deptIds) { if ("(".equals(permissionSql)){ permissionSql = permissionSql + deptId; } else { permissionSql = permissionSql + "," + deptId; } } permissionSql = permissionSql + ")"; // 修改原语句 condition = DEPT_ID +" in " + permissionSql; } else { condition = USER_ID +" = " + userId; } if (StringUtils.isBlank(condition)){ return sql; } Select select = (Select)CCJSqlParserUtil.parse(sql); PlainSelect plainSelect = (PlainSelect)select.getSelectBody(); //取得原SQL的where条件 final Expression expression = plainSelect.getWhere(); //增加新的where条件 final Expression envCondition = CCJSqlParserUtil.parseCondExpression(condition); if (expression == null) { plainSelect.setWhere(envCondition); } else { AndExpression andExpression = new AndExpression(expression, envCondition); plainSelect.setWhere(andExpression); } return plainSelect.toString(); } catch (JSQLParserException e) { logger.error("解析原SQL并构建新SQL错误:" + e); return<p style="color:transparent">来源gao!%daima.com搞$代*!码网</p> sql; } }
以上就是Springboot+mybatis-plus+注解实现数据权限隔离的详细内容,更多请关注gaodaima搞代码网其它相关文章!