平时开发中遇到根据当前用户的角色,只能查看数据权限范围的数据需求。列表实现方案有两种,一是在开发初期就做好判断筛选,但如果这个需求是中途加的,或不希望每个接口都加一遍,就可以方案二加拦截器的方式。在mybatis执行sql前修改语句,限定where范围。
当然拦截器生效后是全局性的,如何保证只对需要的接口进行拦截和转化,就可以应用注解进行识别
因此具体需要哪些步骤就明确了
-
创建注解类 -
创建拦截器实现 InnerInterceptor接口,重写查询方法 -
创建处理类,获取数据权限 SQL 片段,设置where -
将拦截器加到MyBatis-Plus插件中
上代码(基础版)
自定义注解
public UserDataPermission {}
public UserDataPermission {}
拦截器
(callSuper = true)(callSuper = true)publicclassMyDataPermissionInterceptorextendsJsqlParserSupportimplementsInnerInterceptor{
/** * 数据权限处理器 */private MyDataPermissionHandler dataPermissionHandler;
publicvoidbeforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)throws SQLException {if (InterceptorIgnoreHelper.willIgnoreDataPermission(ms.getId())) {return; } PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql); mpBs.sql(this.parserSingle(mpBs.sql(), ms.getId())); }
protectedvoidprocessSelect(Select select, int index, String sql, Object obj){ SelectBody selectBody = select.getSelectBody();if (selectBody instanceof PlainSelect) {this.setWhere((PlainSelect) selectBody, (String) obj); } elseif (selectBody instanceof SetOperationList) { SetOperationList setOperationList = (SetOperationList) selectBody; List<SelectBody> selectBodyList = setOperationList.getSelects(); selectBodyList.forEach(s -> this.setWhere((PlainSelect) s, (String) obj)); } }
/** * 设置 where 条件 * * @param plainSelect 查询对象 * @param whereSegment 查询条件片段 */privatevoidsetWhere(PlainSelect plainSelect, String whereSegment){
Expression sqlSegment = this.dataPermissionHandler.getSqlSegment(plainSelect, whereSegment);if (null != sqlSegment) { plainSelect.setWhere(sqlSegment); } }}
(callSuper = true)(callSuper = true)publicclassMyDataPermissionInterceptorextendsJsqlParserSupportimplementsInnerInterceptor{/*** 数据权限处理器*/private MyDataPermissionHandler dataPermissionHandler;publicvoidbeforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)throws SQLException {if (InterceptorIgnoreHelper.willIgnoreDataPermission(ms.getId())) {return;}PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);mpBs.sql(this.parserSingle(mpBs.sql(), ms.getId()));}protectedvoidprocessSelect(Select select, int index, String sql, Object obj){SelectBody selectBody = select.getSelectBody();if (selectBody instanceof PlainSelect) {this.setWhere((PlainSelect) selectBody, (String) obj);} elseif (selectBody instanceof SetOperationList) {SetOperationList setOperationList = (SetOperationList) selectBody;List<SelectBody> selectBodyList = setOperationList.getSelects();selectBodyList.forEach(s -> this.setWhere((PlainSelect) s, (String) obj));}}/*** 设置 where 条件** @param plainSelect 查询对象* @param whereSegment 查询条件片段*/privatevoidsetWhere(PlainSelect plainSelect, String whereSegment){Expression sqlSegment = this.dataPermissionHandler.getSqlSegment(plainSelect, whereSegment);if (null != sqlSegment) {plainSelect.setWhere(sqlSegment);}}}
拦截器处理器
基础只涉及 = 表达式,要查询集合范围 in 看进阶版用例
publicclassMyDataPermissionHandler{/*** 获取数据权限 SQL 片段** @param plainSelect 查询对象* @param whereSegment 查询条件片段* @return JSqlParser 条件表达式*/public Expression getSqlSegment(PlainSelect plainSelect, String whereSegment) {// 待执行 SQL Where 条件表达式Expression where = plainSelect.getWhere();if (where == null) {where = new HexValue(" 1 = 1 ");}log.info("开始进行权限过滤,where: {},mappedStatementId: {}", where, whereSegment);//获取mapper名称String className = whereSegment.substring(0, whereSegment.lastIndexOf("."));//获取方法名String methodName = whereSegment.substring(whereSegment.lastIndexOf(".") + 1);Table fromItem = (Table) plainSelect.getFromItem();// 有别名用别名,无别名用表名,防止字段冲突报错Alias fromItemAlias = fromItem.getAlias();String mainTableName = fromItemAlias == null ? fromItem.getName() : fromItemAlias.getName();//获取当前mapper 的方法Method[] methods = Class.forName(className).getMethods();//遍历判断mapper 的所以方法,判断方法上是否有 UserDataPermissionfor (Method m : methods) {if (Objects.equals(m.getName(), methodName)) {UserDataPermission annotation = m.getAnnotation(UserDataPermission.class);if (annotation == null) {returnwhere;}// 1、当前用户CodeUser user = SecurityUtils.getUser();// 查看自己的数据// = 表达式EqualsTo usesEqualsTo = new EqualsTo();usesEqualsTo.setLeftExpression(new Column(mainTableName + ".creator_code"));usesEqualsTo.setRightExpression(new StringValue(user.getUserCode()));return new AndExpression(where, usesEqualsTo);}}//说明无权查看,where = new HexValue(" 1 = 2 ");returnwhere;}}
将拦截器加到MyBatis-Plus插件中
如果你之前项目配插件 ,直接用下面方式就行
public MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 添加数据权限插件MyDataPermissionInterceptor dataPermissionInterceptor = new MyDataPermissionInterceptor();// 添加自定义的数据权限处理器dataPermissionInterceptor.setDataPermissionHandler(new MyDataPermissionHandler());interceptor.addInnerInterceptor(dataPermissionInterceptor);interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
但如果你项目之前是依赖包依赖,或有公司内部统一拦截设置好,也可以往MybatisPlusInterceptor进行插入,避免影响原有项目配置
@Beanpublic MyDataPermissionInterceptor myInterceptor(MybatisPlusInterceptor mybatisPlusInterceptor){MyDataPermissionInterceptor sql = new MyDataPermissionInterceptor();sql.setDataPermissionHandler(new MyDataPermissionHandler());List<InnerInterceptor> list = new ArrayList<>();// 添加数据权限插件list.add(sql);// 分页插件mybatisPlusInterceptor.setInterceptors(list);list.add(new PaginationInnerInterceptor(DbType.MYSQL));return sql;}
以上就是简单版的是拦截器修改语句使用
使用方式
在mapper层添加注解即可
List<CustomerAllVO> selectAllCustomerPage(IPage<CustomerAllVO> page, ("customerName")String customerName);
进阶版
基础班只是能用,业务功能没有特别约束,先保证能跑起来
进阶版 解决两个问题:
-
加了角色,用角色决定范围 -
解决不是mapper层自定义sql查询问题。
两个是完全独立的问题 ,可根据情况分开解决
解决不是mapper层自定义sql查询问题。
例如我们名称简单的sql语句 直接在Service层用mybatisPluse自带的方法
xxxxService.list(Wrapper<T> queryWrapper)xxxxService.page(new Page<>(),Wrapper<T> queryWrapper)
以上这种我应该把注解加哪里呢
因为service层,本质上还是调mapper层, 所以还是在mapper层做文章,原来的mapper实现了extends BaseMapper 接口,所以能够查询,我们要做的就是在 mapper层中间套一个中间接口,来方便我们加注解
xxxxxMapper ——》DataPermissionMapper(中间) ——》BaseMapper
根据自身需要,在重写的接口方法上加注解即可,这样就影响原先的代码
publicinterface DataPermissionMapper<T> extends BaseMapper<T> {/*** 根据 ID 查询** @param id 主键ID*/T selectById(Serializable id);/*** 查询(根据ID 批量查询)** @param idList 主键ID列表(不能为 null 以及 empty)*/List<T> selectBatchIds( Collection<? extends Serializable> idList);/*** 查询(根据 columnMap 条件)** @param columnMap 表字段 map 对象*/List<T> selectByMap( Map<String, Object> columnMap);/*** 根据 entity 条件,查询一条记录** @param queryWrapper 实体对象封装操作类(可以为 null)*/T selectOne( Wrapper<T> queryWrapper);/*** 根据 Wrapper 条件,查询总记录数** @param queryWrapper 实体对象封装操作类(可以为 null)*/Integer selectCount( Wrapper<T> queryWrapper);/*** 根据 entity 条件,查询全部记录** @param queryWrapper 实体对象封装操作类(可以为 null)*/List<T> selectList( Wrapper<T> queryWrapper);/*** 根据 Wrapper 条件,查询全部记录** @param queryWrapper 实体对象封装操作类(可以为 null)*/List<Map<String, Object>> selectMaps( Wrapper<T> queryWrapper);/*** 根据 Wrapper 条件,查询全部记录* <p>注意: 只返回第一个字段的值</p>** @param queryWrapper 实体对象封装操作类(可以为 null)*/List<Object> selectObjs( Wrapper<T> queryWrapper);/*** 根据 entity 条件,查询全部记录(并翻页)** @param page 分页查询条件(可以为 RowBounds.DEFAULT)* @param queryWrapper 实体对象封装操作类(可以为 null)*/<E extends IPage<T>> E selectPage(E page, Wrapper<T> queryWrapper);/*** 根据 Wrapper 条件,查询全部记录(并翻页)** @param page 分页查询条件* @param queryWrapper 实体对象封装操作类*/<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, Wrapper<T> queryWrapper);}
解决角色控制查询范围
引入角色,我们先假设有三种角色,按照常规的业务需求,一种是管理员查看全部、一种是部门管理查看本部门、一种是仅查看自己。
有了以上假设,就可以设置枚举类编写业务逻辑, 对是业务逻辑,所以我们只需要更改”拦截器处理器类“
-
建立范围枚举 -
建立角色枚举以及范围关联关系 -
重写拦截器处理方法
范围枚举
publicenum DataScope {// Scope 数据权限范围 : ALL(全部)、DEPT(部门)、MYSELF(自己)ALL("ALL"),DEPT("DEPT"),MYSELF("MYSELF");privateString name;}
角色枚举
publicenum DataPermission {// 枚举类型根据范围从前往后排列,避免影响getScope// Scope 数据权限范围 : ALL(全部)、DEPT(部门)、MYSELF(自己)DATA_MANAGER("数据管理员", "DATA_MANAGER",DataScope.ALL),DATA_AUDITOR("数据审核员", "DATA_AUDITOR",DataScope.DEPT),DATA_OPERATOR("数据业务员", "DATA_OPERATOR",DataScope.MYSELF);privateString name;privateString code;private DataScope scope;publicstaticString getName(String code) {for (DataPermission type : DataPermission.values()) {if (type.getCode().equals(code)) {returntype.getName();}}returnnull;}publicstaticString getCode(String name) {for (DataPermission type : DataPermission.values()) {if (type.getName().equals(name)) {returntype.getCode();}}returnnull;}publicstatic DataScope getScope(Collection<String> code) {for (DataPermission type : DataPermission.values()) {for (String v : code) {if (type.getCode().equals(v)) {returntype.getScope();}}}return DataScope.MYSELF;}}
重写拦截器处理类 MyDataPermissionHandler
publicclassMyDataPermissionHandler{private RemoteRoleService remoteRoleService;private RemoteUserService remoteUserService;/*** 获取数据权限 SQL 片段** @param plainSelect 查询对象* @param whereSegment 查询条件片段* @return JSqlParser 条件表达式*/public Expression getSqlSegment(PlainSelect plainSelect, String whereSegment) {remoteRoleService = SpringUtil.getBean(RemoteRoleService.class);remoteUserService = SpringUtil.getBean(RemoteUserService.class);// 待执行 SQL Where 条件表达式Expression where = plainSelect.getWhere();if (where == null) {where = new HexValue(" 1 = 1 ");}log.info("开始进行权限过滤,where: {},mappedStatementId: {}", where, whereSegment);//获取mapper名称String className = whereSegment.substring(0, whereSegment.lastIndexOf("."));//获取方法名String methodName = whereSegment.substring(whereSegment.lastIndexOf(".") + 1);Table fromItem = (Table) plainSelect.getFromItem();// 有别名用别名,无别名用表名,防止字段冲突报错Alias fromItemAlias = fromItem.getAlias();String mainTableName = fromItemAlias == null ? fromItem.getName() : fromItemAlias.getName();//获取当前mapper 的方法Method[] methods = Class.forName(className).getMethods();//遍历判断mapper 的所以方法,判断方法上是否有 UserDataPermissionfor (Method m : methods) {if (Objects.equals(m.getName(), methodName)) {UserDataPermission annotation = m.getAnnotation(UserDataPermission.class);if (annotation == null) {returnwhere;}// 1、当前用户CodeUser user = SecurityUtils.getUser();// 2、当前角色即角色或角色类型(可能多种角色)Set<String> roleTypeSet = remoteRoleService.currentUserRoleType();DataScope scopeType = DataPermission.getScope(roleTypeSet);switch (scopeType) {// 查看全部case ALL:returnwhere;case DEPT:// 查看本部门用户数据// 创建IN 表达式// 创建IN范围的元素集合List<String> deptUserList = remoteUserService.listUserCodesByDeptCodes(user.getDeptCode());// 把集合转变为JSQLParser需要的元素列表ItemsList deptList = new ExpressionList(deptUserList.stream().map(StringValue::new).collect(Collectors.toList()));InExpression inExpressiondept = new InExpression(new Column(mainTableName + ".creator_code"), deptList);return new AndExpression(where, inExpressiondept);case MYSELF:// 查看自己的数据// = 表达式EqualsTo usesEqualsTo = new EqualsTo();usesEqualsTo.setLeftExpression(new Column(mainTableName + ".creator_code"));usesEqualsTo.setRightExpression(new StringValue(user.getUserCode()));return new AndExpression(where, usesEqualsTo);default:break;}}}//说明无权查看,where = new HexValue(" 1 = 2 ");returnwhere;}}
以上就是全篇知识点, 需要注意的点可能有:
-
记得把拦截器加到MyBatis-Plus的插件中,确保生效 -
要有一个业务赛选标识字段, 这里用的创建人 creator_code, 也可以用dept_code等等
如喜欢本文,请点击右上角,把文章分享到朋友圈
如有想了解学习的技术点,请留言给若飞安排分享
因公众号更改推送规则,请点“在看”并加“星标”第一时间获取精彩技术分享
·END·
相关阅读:
-
一张图看懂微服务架构路线
-
基于Spring Cloud的微服务架构分析 -
微服务等于Spring Cloud?了解微服务架构和框架
-
如何构建基于 DDD 领域驱动的微服务? -
微服务架构实施原理详解
-
微服务的简介和技术栈 -
微服务场景下的数据一致性解决方案 -
设计一个容错的微服务架构
作者:一湫1959
来源:blog.csdn.net/yiqiu1959/article/details/128923821
版权申明:内容来源网络,仅供学习研究,版权归原创者所有。如有侵权烦请告知,我们会立即删除并表示歉意。谢谢!
我们都是架构师!

关注架构师(JiaGouX),添加“星标”
获取每天技术干货,一起成为牛逼架构师
技术群请加若飞:1321113940 进架构师群
投稿、合作、版权等邮箱:admin@137x.com

