什么是数据权限

数据权限是指系统根据用户的角色、职位或其他属性,控制用户能够访问的数据范围。与传统的功能权限(菜单、按钮权限)不同,数据权限关注的是数据行级别的访问控制。

常见的数据权限控制方式包括:

  • 部门数据权限:只能访问本部门数据

  • 个人数据权限:只能访问自己的数据

  • 自定义数据范围:通过特定规则限制数据访问

MyBatis-Plus实现数据权限的方案

实现完整例子

下面是一个完整的基于MyBatis-Plus和Spring Security的数据权限实现示例:

 1. 数据权限配置类

@Configuration
public class MybatisConfig {@Beanpublic ConfigurationCustomizer mybatisConfigurationCustomizer(){return configuration -> configuration.setObjectWrapperFactory(new MapWrapperFactory());}@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 1.添加数据权限插件interceptor.addInnerInterceptor(new DataPermissionInterceptor(new DataPressionConfig()));PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();// 分页插件paginationInnerInterceptor.setOptimizeJoin(false);paginationInnerInterceptor.setOverflow(true);paginationInnerInterceptor.setDbType(DbType.POSTGRE_SQL);interceptor.addInnerInterceptor(paginationInnerInterceptor);return interceptor;}
}

     2. 数据权限拦截器
    @Slf4j
    @Component
    public class DataPressionConfig implements DataPermissionHandler {@Overridepublic Expression getSqlSegment(Expression where, String mappedStatementId) {try {if(null==mappedStatementId){return null;}Class<?> mapperClazz = Class.forName(mappedStatementId.substring(0, mappedStatementId.lastIndexOf(".")));String methodName = mappedStatementId.substring(mappedStatementId.lastIndexOf(".") + 1);// 获取自身类中的所有方法,不包括继承。与访问权限无关Method[] methods = mapperClazz.getDeclaredMethods();for (Method method : methods) {DataScope dataScopeAnnotationMethod = method.getAnnotation(DataScope.class);if(null==dataScopeAnnotationMethod){continue;}//spring aoc里拿方法参数Parameter[] parameters= method.getParameters();if (parameters.length > 0) {log.info("方法参数:" +  dataScopeAnnotationMethod.oneselfScopeName() );}if (ObjectUtils.isEmpty(dataScopeAnnotationMethod) || !dataScopeAnnotationMethod.enabled()) {continue;}if (method.getName().equals(methodName) || (method.getName() + "_COUNT").equals(methodName) || (method.getName() + "_count").equals(methodName)) {return buildDataScopeByAnnotation(dataScopeAnnotationMethod,mappedStatementId);}}} catch (ClassNotFoundException e) {e.printStackTrace();}return null;}/*** DataScope注解方式,拼装数据权限** @param dataScope* @return*/private Expression buildDataScopeByAnnotation(DataScope dataScope,String mapperId) {Map<String, Object> params = DataPermissionContext.getParams();if (params == null || params.isEmpty()) {return null;}Object areaCodes = params.get(mapperId);List<String> dataScopeDeptIds=  (List<String>) areaCodes;// 获取注解信息String tableAlias = dataScope.tableAlias();String areaCodes= dataScope.areaCodes();Expression expression = buildDataScopeExpression(tableAlias,   areaCodes, dataScopeDeptIds);return expression == null ? null : new Parenthesis(expression);}/*** 拼装数据权限** @param tableAlias        表别名* @param oneselfScopeName  本人限制范围的字段名称* @param dataScopeDeptIds  数据权限部门ID集合,去重* @return*/private Expression buildDataScopeExpression(String tableAlias,  String areaCodes, List<String> dataScopeDeptIds) {/*** 构造部门里行政区划 area_code 的in表达式。*/try {String sql=tableAlias + "." + areaCodes+" in (";for(String areaCode:dataScopeDeptIds){sql+="'"+areaCode+"',";}sql=sql.substring(0,sql.length()-1)+")";Expression selectExpression = CCJSqlParserUtil.parseCondExpression(sql, true);return selectExpression;} catch (JSQLParserException e) {throw new RuntimeException(e);}}}

    3. 存储spring aop切面拿到的数据

         

      public class DataPermissionContext {private static final ThreadLocal<Map<String, Object>> CONTEXT = new ThreadLocal<>();public static void setParams(Map<String, Object> params) {CONTEXT.set(params);}public static Map<String, Object> getParams() {return CONTEXT.get();}public static void clear() {CONTEXT.remove();}
      }

         4. 定义数据权限注解
        @Inherited
        @Target({ElementType.METHOD, ElementType.TYPE})
        @Retention(RetentionPolicy.RUNTIME)
        public @interface DataScope {/*** 是否生效,默认true-生效*/boolean enabled() default true;/*** 表别名*/String tableAlias() default "";/*** 本人限制范围的字段名称*/String areaCodes() default "area_code";}
        5. 实现AOP切面
        @Slf4j
        @Aspect
        @Component
        public class DataAspet {@Pointcut("@annotation(DataScope)")public void logPoinCut() {}@Before("logPoinCut()")public void saveSysLog(JoinPoint joinPoint) {//从切面织入点处通过反射机制获取织入点处的方法MethodSignature signature = (MethodSignature) joinPoint.getSignature();//获取切入点所在的方法Method method = signature.getMethod();DataScope scope = method.getAnnotation(DataScope.class);Map<String, Object> paramValues = new HashMap<>();Object[] args = joinPoint.getArgs();Parameter[] parameters = method.getParameters();if(null!=parameters&&parameters.length>0) {//添加到最后一个参数log.info("参数名称:{}",signature.getName()+":"+signature.getDeclaringTypeName());paramValues.put(signature.getDeclaringTypeName()+"."+signature.getName(), args[parameters.length-1]);DataPermissionContext.setParams(paramValues);}else{DataPermissionContext.setParams(null);}}}

        6. mapper里注解使用数据权限

        tableAlias里你的sql里面要插入数据权限字段的表别名。

        比如:

        select count(*) as total,d.type as type from bus_device d group by d.type

        spring aop 会读取mapper方法最后一个参数,然后切入Sql变成

        select count(*) as total,d.type as type from bus_device d where

        d.area_code in(#{areaCodes} )  group by d.type

            @DataScope(tableAlias = "d")List<DeviceTypeCountDto> listByApplicationCategory(@Param(  @Param("type") String type,List<String> areaCodes);
        

        注意事项

        1. 性能考虑:数据权限过滤会增加SQL复杂度,可能影响查询性能,特别是对于大数据量表。可以考虑添加适当的索引优化。

        2. SQL注入风险:在拼接SQL时要特别注意防止SQL注入,建议使用预编译参数。

        3. 缓存问题:如果使用了缓存,需要注意数据权限可能导致缓存命中率下降或数据泄露问题。

        4. 多租户场景:在多租户系统中,数据权限通常需要与租户隔离一起考虑。

        5. 复杂查询:对于复杂的多表关联查询,数据权限条件可能需要更精细的控制。

        通过以上方案,我们可以灵活地在MyBatis-Plus中实现各种数据权限控制需求,根据项目实际情况选择最适合的实现方式。

        本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
        如若转载,请注明出处:http://www.pswp.cn/diannao/87083.shtml
        繁体地址,请注明出处:http://hk.pswp.cn/diannao/87083.shtml
        英文地址,请注明出处:http://en.pswp.cn/diannao/87083.shtml

        如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

        相关文章

        大模型——Dify 与 Browser-use 结合使用

        大模型——Dify 与 Browser-use 结合使用 Dify 与 Browser-use 的结合使用,能够通过 AI 决策与自动化交互的协同,构建智能化、场景化的业务流程。 以下是两者的整合思路与技术落地方案: 一、核心组合逻辑 分工定位 Dify:作为AI模型调度中枢,负责自然语言理解、决策生成、…

        transformer demo

        import torch import torch.nn as nn import torch.nn.functional as F import math import numpy as np import pytestclass PositionalEncoding(nn.Module):def __init__(self, d_model, max_seq_length5000):super(PositionalEncoding, self).__init__()# 创建位置编码矩阵p…

        centos 8.3(阿里云服务器)mariadb由系统自带版本(10.3)升级到10.6

        1. 备份数据库 在进行任何升级操作前&#xff0c;务必备份所有数据库&#xff1a; mysqldump -u root -p --all-databases > all_databases_backup.sql # 或者为每个重要数据库单独备份 mysqldump -u root -p db_name1 > db_name1_backup.sql mysqldump -u root -p db…

        如何稳定地更新你的大模型知识(算法篇)

        目录 在线强化学习的稳定知识获取机制:算法优化与数据策略一、算法层面的稳定性控制机制二、数据处理策略的稳定性保障三、训练过程中的渐进式优化策略四、环境设计与反馈机制的稳定性影响五、稳定性保障的综合应用策略六、总结与展望通过强化学习来让大模型学习高层语义知识,…

        图的遍历模板

        图的遍历 BFS 求距离 #include<bits/stdc.h>using namespace std;int n, m, k,q[20001],dist[20001]; vector<int> edge[20001];int main(){scanf("%d%d%d",&n,&m,&k);for (int i 1;i<m;i){int x,y;scanf("%d%d",&x,&am…

        Java集合 - LinkedList底层源码解析

        以下是基于 JDK 8 的 LinkedList 深度源码解析&#xff0c;涵盖其数据结构、核心方法实现、性能特点及使用场景。我们从 类结构、Node节点、插入/删除/访问操作、线程安全、性能对比 等角度进行详细分析 一、类结构与继承关系 1. 类定义 public class LinkedList<E> e…

        Pytorch 卷积神经网络参数说明一

        系列文章目录 文章目录 系列文章目录前言一、卷积层的定义1.常见的卷积操作2. 感受野3. 如何理解参数量和计算量4.如何减少计算量和参数量 二、神经网络结构&#xff1a;有些层前面文章说过&#xff0c;不全讲1. 池化层&#xff08;下采样&#xff09;2. 上采样3. 激活层、BN层…

        C++ 中的 iostream 库:cin/cout 基本用法

        iostream 是 C 标准库中用于输入输出操作的核心库&#xff0c;它基于面向对象的设计&#xff0c;提供了比 C 语言的 stdio.h 更强大、更安全的 I/O 功能。下面详细介绍 iostream 库中最常用的输入输出工具&#xff1a;cin 和 cout。 一、 基本概念 iostream 库&#xff1a;包…

        SAP复制一个自定义移动类型

        SAP复制移动类型 在SAP系统中&#xff0c;复制移动类型201可以通过事务码OMJJ或SPRO路径完成&#xff0c;用于创建自定义的移动类型以满足特定业务需求。 示例操作步骤 进入OMJJ事务码&#xff1a; 打开事务码OMJJ&#xff0c;选择“移动类型”选项。 复制移动类型&#xff…

        Bambu Studio 中的“回抽“与“装填回抽“的区别

        回抽 装填回抽: Bambu Studio 中的“回抽” (Retraction) 和“装填回抽”(Prime/Retract) 是两个不同的概念&#xff0c;它们都与材料挤出机的操作过程相关&#xff0c;但作用和触发条件有所不同。 回抽(Retraction): 回抽的作用, 在打印机移动到另一个位置之前&#xff0c;将…

        危化品安全监测数据分析挖掘范式:从被动响应到战略引擎的升维之路

        在危化品生产的复杂生态系统中,安全不仅仅是合规性要求,更是企业生存和发展的生命线。传统危化品安全生产风险监测预警系统虽然提供了基础保障,但其“事后响应”和“单点预警”的局限性日益凸显。我们正处在一个由大数据、人工智能、数字孪生和物联网技术驱动的范式变革前沿…

        C++ RPC 远程过程调用详细解析

        一、RPC 基本原理 RPC (Remote Procedure Call) 是一种允许程序调用另一台计算机上子程序的协议,而不需要程序员显式编码这个远程交互细节。其核心思想是使远程调用看起来像本地调用一样。 RPC 工作流程 客户端调用:客户端调用本地存根(stub)方法参数序列化:客户端存根将参…

        Python:操作 Excel 预设色

        💖亲爱的技术爱好者们,热烈欢迎来到 Kant2048 的博客!我是 Thomas Kant,很开心能在CSDN上与你们相遇~💖 本博客的精华专栏: 【自动化测试】 【测试经验】 【人工智能】 【Python】 Python 操作 Excel 系列 读取单元格数据按行写入设置行高和列宽自动调整行高和列宽水平…

        中科院1区|IF10+:加大医学系团队利用GPT-4+电子病历分析,革新肝硬化并发症队列识别

        中科院1区|IF10&#xff1a;加大医学系团队利用GPT-4电子病历分析&#xff0c;革新肝硬化并发症队列识别 在当下的科研领域&#xff0c;人工智能尤其是大语言模型的迅猛发展&#xff0c;正为各个学科带来前所未有的机遇与变革。在医学范畴&#xff0c;从疾病的早期精准筛查&am…

        Python学习小结

        bg&#xff1a;记录一下&#xff0c;怕忘了&#xff1b;先写一点&#xff0c;后面再补充。 1、没有方法重载 2、字段都是公共字段 3、都是类似C#中顶级语句的写法 4、对类的定义直接&#xff1a; class Student: 创建对象不需要new关键字&#xff0c;直接stu Student() 5、方…

        QCustomPlot 中实现拖动区域放大‌与恢复

        1、拖动区域放大‌ 在 QCustomPlot 中实现 ‌拖动区域放大‌&#xff08;即通过鼠标左键拖动绘制矩形框选区域进行放大&#xff09;的核心方法是设置 SelectionRectMode。具体操作步骤&#xff1a; 1‌&#xff09;禁用拖动模式‌ 确保先关闭默认的图表拖动功能&#xff08;否…

        如何将文件从 iPhone 传输到闪存驱动器

        您想将文件从 iPhone 或 iPad 传输到闪存盘进行备份吗&#xff1f;这是一个很好的决定&#xff0c;但您需要先了解一些实用的方法。虽然 Apple 生态系统在很大程度上是封闭的&#xff0c;但您可以使用一些实用工具将文件从 iPhone 或 iPad 传输到闪存盘。下文提供了这些行之有效…

        互联网大厂Java求职面试:云原生架构与微服务设计中的复杂挑战

        互联网大厂Java求职面试&#xff1a;云原生架构与微服务设计中的复杂挑战 面试官开场白 面试官&#xff08;严肃模式开启&#xff09;&#xff1a;郑薪苦&#xff0c;欢迎来到我们的技术面试环节。我是本次面试的技术总监&#xff0c;接下来我们将围绕云原生架构、微服务设计、…

        leetcode-hot-100 (链表)

        1. 相交链表 题目链接&#xff1a;相交链表 题目描述&#xff1a;给你两个单链表的头节点 headA 和 headB &#xff0c;请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点&#xff0c;返回 null 。 解答&#xff1a; 其实这道题目我一开始没太看懂题目给…

        Web前端基础之HTML

        一、浏览器 火狐浏览器、谷歌浏览器(推荐)、IE浏览器 推荐谷歌浏览器原因&#xff1a; 1、简洁大方,打开速度快 2、开发者调试工具&#xff08;右键空白处->检查&#xff0c;打开调试模式&#xff09; 二、开发工具 核心IDE工具 Visual Studio Code (VS Code)‌ 微软开发…