最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Mybatis攔截器實現(xiàn)數(shù)據(jù)權限的示例代碼

 更新時間:2022年03月11日 11:03:06   作者:chaojunma  
在我們?nèi)粘i_發(fā)過程中,通常會涉及到數(shù)據(jù)權限問題,本文主要介紹了Mybatis攔截器實現(xiàn)數(shù)據(jù)權限的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

在我們?nèi)粘i_發(fā)過程中,通常會涉及到數(shù)據(jù)權限問題,下面以我們常見的一種場景舉例:

一個公司有很多部門,每個人所處的部門和角色也不同,所以數(shù)據(jù)權限也可能不同,比如超級管理員可以查看某張

表的素有信息,部門領導可以查看該部門下的相關信息,部門普通人員只可以查看個人相關信息,而且由于角色的

不同,各個角色所能查看到的數(shù)據(jù)庫字段也可能不相同,那么此處就涉及到了數(shù)據(jù)權限相關的問題。那么我們該如

何處理數(shù)據(jù)權限相關的問題呢?我們提供一種通過Mybatis攔截器實現(xiàn)的方式,下面我們來具體實現(xiàn)一下

pom.xml依賴

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.13.RELEASE</version>
</parent>
 
<properties>
    <java.version>1.8</java.version>
    <mybatis-plus.version>3.2.0</mybatis-plus.version>
</properties>
 
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>${mybatis-plus.version}</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

application.yml文件

server:
  port: 80
 
spring:
  application:
    name: data-scope
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    druid:
      # 驗證連接是否有效。此參數(shù)必須設置為非空字符串,下面三項設置成true才能生效
      validation-query: SELECT 1
      # 連接是否被空閑連接回收器(如果有)進行檢驗. 如果檢測失敗, 則連接將被從池中去除
      test-while-idle: true
      # 是否在從池中取出連接前進行檢驗, 如果檢驗失敗, 則從池中去除連接并嘗試取出另一個
      test-on-borrow: true
      # 是否在歸還到池中前進行檢驗
      test-on-return: false
      # 連接在池中最小生存的時間,單位是毫秒
      min-evictable-idle-time-millis: 30000
 
#mybatis配置
mybatis-plus:
  type-aliases-package: com.mk.entity
  mapper-locations: classpath:mapper/**/*.xml
  global-config:
    db-config:
      id-type: auto
      field-strategy: not_empty
      logic-delete-value: 1
      logic-not-delete-value: 0
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    call-setters-on-nulls: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

代碼實現(xiàn)

DataScode.java

@Data
public class DataScope {
 
    // sql過濾條件
    String sqlCondition;
 
    // 需要過濾的結果字段
    String[] filterFields;
 
}

MybatisPlusConfig.java

@Configuration
public class MybatisPlusConfig {
 
    @Bean
    @ConditionalOnMissingBean
    public DataScopeInterceptor dataScopeInterceptor() {
        return new DataScopeInterceptor();
    }
 
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType(DbType.MYSQL.getDb());
        return page;
    }
 
    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(MybatisConfiguration configuration) {
                configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());
            }
        };
    }
}

DataScopeInterceptor.java

@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class,ResultHandler.class})})
public class DataScopeInterceptor implements Interceptor {
 
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
 
        log.info("執(zhí)行intercept方法:{}", invocation.toString());
 
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
 
        // 查找參數(shù)中包含DataScope類型的參數(shù)
        DataScope dataScope = findDataScopeObject(parameterObject);
        if (dataScope == null) {
            return invocation.proceed();
        }
 
 
        if (!ObjectUtils.isEmpty(dataScope.getSqlCondition())) {
            // id為執(zhí)行的mapper方法的全路徑名,如com.mapper.UserMapper
            String id = ms.getId();
 
            // sql語句類型 select、delete、insert、update
            String sqlCommandType = ms.getSqlCommandType().toString();
 
            // 僅攔截 select 查詢
            if (!sqlCommandType.equals(SqlCommandType.SELECT.toString())) {
                return invocation.proceed();
            }
 
            BoundSql boundSql = ms.getBoundSql(parameterObject);
            String origSql = boundSql.getSql();
            log.info("原始SQL: {}", origSql);
 
            // 組裝新的 sql
            String newSql = String.format("%s%s%s%s", "select * from (", origSql, ") ", dataScope.getSqlCondition());
 
            // 重新new一個查詢語句對象
            BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
                    boundSql.getParameterMappings(), boundSql.getParameterObject());
 
            // 把新的查詢放到statement里
            MappedStatement newMs = newMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
            for (ParameterMapping mapping : boundSql.getParameterMappings()) {
                String prop = mapping.getProperty();
                if (boundSql.hasAdditionalParameter(prop)) {
                    newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
                }
            }
 
            Object[] queryArgs = invocation.getArgs();
            queryArgs[0] = newMs;
 
            log.info("改寫的SQL: {}", newSql);
        }
 
        Object result = invocation.proceed();
 
        return handleReslut(result, Arrays.asList(dataScope.getFilterFields()));
    }
 
    /**
     * 定義一個內(nèi)部輔助類,作用是包裝 SQL
     */
    class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;
        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
 
    }
 
    private MappedStatement newMappedStatement (MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new
                MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }
 
    @Override
    public Object plugin(Object target) {
        log.info("plugin方法:{}", target);
 
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
 
    }
 
    @Override
    public void setProperties(Properties properties) {
        // 獲取屬性
        // String value1 = properties.getProperty("prop1");
        log.info("properties方法:{}", properties.toString());
    }
 
 
 
    /**
     * 查找參數(shù)是否包括DataScope對象
     *
     * @param parameterObj 參數(shù)列表
     * @return DataScope
     */
    private DataScope findDataScopeObject(Object parameterObj) {
        if (parameterObj instanceof DataScope) {
            return (DataScope) parameterObj;
        } else if (parameterObj instanceof Map) {
            for (Object val : ((Map<?, ?>) parameterObj).values()) {
                if (val instanceof DataScope) {
                    return (DataScope) val;
                }
            }
        }
        return null;
    }
 
 
    public Object handleReslut(Object returnValue, List<String> filterFields){
        if(returnValue != null && !ObjectUtils.isEmpty(filterFields)){
            if (returnValue instanceof ArrayList<?>){
                List<?> list = (ArrayList<?>) returnValue;
                List<Object> newList  = new ArrayList<Object>();
                if (1 <= list.size()) {
                    for(Object object:list){
                        if (object instanceof Map) {
                            Map map = (Map) object;
                            for (String key : filterFields) {
                                map.remove(key);
                            }
                            newList.add(map);
                        } else {
                            newList.add(decrypt(filterFields, object));
                        }
                    }
                    returnValue = newList;
                }
            } else {
                if (returnValue instanceof Map) {
                    Map map = (Map) returnValue;
                    for (String key : filterFields) {
                        map.remove(key);
                    }
                } else {
                    returnValue = decrypt(filterFields, returnValue);
                }
            }
        }
        return returnValue;
    }
 
 
    public static <T> T decrypt(List<String> filterFields, T t) {
        Field[] declaredFields = t.getClass().getDeclaredFields();
        try {
            if (declaredFields != null && declaredFields.length > 0) {
                for (Field field : declaredFields) {
                    if (filterFields.contains(field.getName())) {
                        field.setAccessible(true);
                        field.set(t, null);
                        field.setAccessible(false);
                    }
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
 
        return t;
    }
}

SalariesMapper.xml

<mapper namespace="com.mk.mapper.SalariesMapper">
    <select id="pageList" resultType="com.mk.entity.Salaries">
        SELECT * from salaries where salary between #{start} and #{end}
    </select>
 
    <select id="getByEmpNo" resultType="java.util.Map">
        select * from salaries where emp_no = #{empNo} limit 0,1
    </select>
</mapper>

SalariesMapper.java

@Mapper
public interface SalariesMapper extends BaseMapper<Salaries> {
 
    List<Salaries> pageList(DataScope dataScope, @Param("start") int start,  @Param("end") int end, Page<Salaries> page);
 
    Map<String, Object> getByEmpNo(DataScope dataScope, @Param("empNo") int empNo);
}

SalariesService.java

@Service
public class SalariesService extends ServiceImpl<SalariesMapper, Salaries> {
 
    @Autowired
    private SalariesMapper salariesMapper;
 
    public List<Salaries> getList(){
        Page<Salaries> page = new Page<>(1, 10);
        DataScope dataScope = new DataScope();
        // 設置查詢條件
        dataScope.setSqlCondition("s where 1=1 and s.emp_no = '10001'");
        // 將結果集過濾掉salary和toDate字段
        dataScope.setFilterFields(new String[]{"salary", "toDate"});
        return salariesMapper.pageList(dataScope, 60000, 70000, page);
 
    }
 
    public Map<String, Object> getByEmpNo() {
        DataScope dataScope = new DataScope();
        // 將結果集過濾掉salary和toDate字段
        dataScope.setFilterFields(new String[]{"salary", "toDate"});
        return salariesMapper.getByEmpNo(dataScope, 10001);
    }
}

啟動服務,執(zhí)行相關操作,sql在執(zhí)行之前會執(zhí)行DataScopeInterceptor攔截器中的邏輯,從而改變sql,具體的

相關操作就是將原來的sql語句origSql在外層包裝一層過濾條件,如:select * from (origSql) 過濾條件,

此處的過濾條件要封裝到DataScope對象中,例如:dataScope.setSqlCondition("s where 1=1 and

s.emp_no = '10001'") , 那么在經(jīng)過攔截器處理以后要執(zhí)行的sql語句為

select * from (origSql) s where 1=1 and s.emp_no = '10001', 從而實現(xiàn)數(shù)據(jù)權限相操作,當然此處的過濾條件只是為了演示效果舉的一個例子

而已,在實際開發(fā)過程中要根據(jù)用戶角色等等設置具體的過濾條件。

到此這篇關于Mybatis攔截器實現(xiàn)數(shù)據(jù)權限的示例代碼的文章就介紹到這了,更多相關Mybatis攔截器實現(xiàn)數(shù)據(jù)權限內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java中comparator接口和Comparable接口的比較解析

    Java中comparator接口和Comparable接口的比較解析

    這篇文章主要介紹了Java中comparator接口和Comparable接口的比較解析,Java提供了一個用于比較的接口Comparator和Comparable接口,提供了一個比較的方法,所有實現(xiàn)該接口的類,都動態(tài)的實現(xiàn)了該比較方法,需要的朋友可以參考下
    2023-08-08
  • Linux環(huán)境下的Java(JDBC)連接openGauss數(shù)據(jù)庫實踐記錄

    Linux環(huán)境下的Java(JDBC)連接openGauss數(shù)據(jù)庫實踐記錄

    這篇文章主要介紹了Linux環(huán)境下的Java(JDBC)連接openGauss數(shù)據(jù)庫實踐記錄,需要的朋友可以參考下
    2022-11-11
  • SpringBoot日程管理Quartz與定時任務Task實現(xiàn)詳解

    SpringBoot日程管理Quartz與定時任務Task實現(xiàn)詳解

    定時任務是企業(yè)級開發(fā)中必不可少的組成部分,諸如長周期業(yè)務數(shù)據(jù)的計算,例如年度報表,諸如系統(tǒng)臟數(shù)據(jù)的處理,再比如系統(tǒng)性能監(jiān)控報告,還有搶購類活動的商品上架,這些都離不開定時任務。本節(jié)將介紹兩種不同的定時任務技術
    2022-09-09
  • Springboot參數(shù)校驗之分組校驗、嵌套校驗的實現(xiàn)

    Springboot參數(shù)校驗之分組校驗、嵌套校驗的實現(xiàn)

    日常開發(fā)中,免不了需要對請求參數(shù)進行校驗,諸如判空,長度,正則,集合等,復雜一點的請求參數(shù)可能會包含嵌套,分組校驗,本文就詳細的介紹一下,感興趣的可以了解一下
    2023-08-08
  • java hashtable實現(xiàn)代碼

    java hashtable實現(xiàn)代碼

    這篇文章介紹了java hashtable實現(xiàn)代碼,有需要的朋友可以參考一下
    2013-10-10
  • Java異常中toString()和getMessage()區(qū)別

    Java異常中toString()和getMessage()區(qū)別

    在java異常體系中,要打印異常信息,可以通過:e.getMessage() 、 e.toString() e.printStackTrace() 等方法打印,本文主要介紹了Java異常中toString()和getMessage()區(qū)別,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • springboot的pom.xml配置方式

    springboot的pom.xml配置方式

    這篇文章主要介紹了springboot的pom.xml配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • 深入理解springboot中配置文件application.properties

    深入理解springboot中配置文件application.properties

    本文主要介紹了springboot中配置文件application.properties,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • Java中的ThreadLocal線程變量詳解

    Java中的ThreadLocal線程變量詳解

    這篇文章主要介紹了Java中的ThreadLocal線程變量詳解,ThreadLocal叫做線程變量,意思是在ThreadLocal中填充的變量屬于當前線程,該變量對其他線程而言是隔離的,它是用來提供線程內(nèi)部的局部變量,需要的朋友可以參考下
    2024-01-01
  • 理解Java垃圾回收

    理解Java垃圾回收

    這篇文章主要幫助大家理解Java垃圾回收,通過實例學習java垃圾回收,什么是垃圾回收,感興趣的小伙伴們可以參考一下
    2016-03-03

最新評論

吉林省| 卢龙县| 晴隆县| 新闻| 攀枝花市| 乐至县| 高邮市| 南城县| 莱阳市| 资中县| 江孜县| 安顺市| 丁青县| 凤冈县| 公安县| 博爱县| 宁阳县| 政和县| 明水县| 女性| 康马县| 蚌埠市| 葫芦岛市| 湄潭县| 阳泉市| 周至县| 集贤县| 泸定县| 崇义县| 班玛县| 万宁市| 宁晋县| 武宣县| 丰镇市| 衡阳市| 清徐县| 宜都市| 汉寿县| 获嘉县| 芒康县| 嘉峪关市|