• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Springboot+mybatis-plus+注解实现数据权限隔离

springboot 搞代码 4年前 (2022-01-05) 41次浏览 已收录 0个评论

本文将结合实例代码,介绍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搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Springboot+mybatis-plus+注解实现数据权限隔离
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址