Mybatis 适配多数据源 关键字查扣问题

打印 上一主题 下一主题

主题 905|帖子 905|积分 2715

Mybatis 适配多数据源 关键字查扣问题

前言

最近项目使用Mybatis拦截器对国产化数据源数据进行关键字处置惩罚,以下记载如何将拦截器集成到项目中以及在使用过程中踩过的一些小坑
1.Myabtis拦截器是什么?

MyBatis答应使用者在映射语句实行过程中的某一些指定的节点进行拦截调用,通过织入拦截器,在不同节点修改一些实行过程中的关键属性,从而影响SQL的生成、实行和返回结果,如:来影响Mapper.xml到SQL语句的生成、实行SQL前对预编译的SQL实行参数的修改、SQL实行后返回结果到Mapper接口方法返参POJO对象的类型转换和封装等。
2,Mybatis核心对象

从MyBatis代码实现的角度来看,MyBatis的主要的核心部件有以下几个:
Configuration:初始化基础设置,比如MyBatis的别名等,一些重要的类型对象,如插件,映射器,ObjectFactory和typeHandler对象,MyBatis所有的设置信息都维持在Configuration对象之中。
SqlSessionFactory:SqlSession工厂。
SqlSession:作为MyBatis工作的主要顶层API,表示和数据库交互的会话,完成必要的数据库增删改查功能。
Executor:MyBatis的内部实行器,它负责调用StatementHandler操作数据库,并把结果集通过ResultSetHandler进行自动映射,另外,它还处置惩罚二级缓存的操作。
StatementHandler:MyBatis直接在数据库实行SQL脚本的对象。另外它也实现了MyBatis的一级缓存。
ParameterHandler:负责将用户通报的参数转换成JDBC Statement所必要的参数。是MyBatis实现SQL入参设置的对象。
ResultSetHandler:负责将JDBC返回的ResultSet结果集对象转换成List类型的集合。是MyBatis把ResultSet集合映射成POJO的接口对象。
TypeHandler:负责Java数据类型和JDBC数据类型之间的映射和转换。
MappedStatement:MappedStatement维护了一条<select|update|delete|insert>节点的封装。
SqlSource :负责根据用户通报的parameterObject,动态地生成SQL语句,将信息封装到BoundSql对象中,并返回。
BoundSql:表示动态生成的SQL语句以及相应的参数信息。
3,如何使用

3.1 起首先容一下mybatis拦截器拦截的类型


自定义拦截器必须使用@Intercepts注解,并实现Interceptor接口
@Intercepts注解:代表该类是一个拦截器
@Signature注解:表示要拦截哪一个方法
同时@Signature注解有三个参数
  1. type:MyBatis拦截器默认可以拦截的类型只有四种,即四种接口类型Executor、StatementHandler、ParameterHandler和ResultSetHandler,type可以选取四种类型中的一个
  2. method:对应接口中的方法,比图Executor的query方法
  3. args:对应某个接口方法中的参数
复制代码
3.2 代码示例

代码中使用的mybatis-plus的版本
  1.             <dependency>
  2.                 <groupId>com.baomidou</groupId>
  3.                 <artifactId>mybatis-plus-boot-starter</artifactId>
  4.                 <version>3.4.3</version>
  5.             </dependency>
复制代码
拦截器类
  1. @Component
  2. @Intercepts({@Signature(method = "query", type = Executor.class, args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
  3.         @Signature(
  4.                 type = Executor.class,
  5.                 method = "update",
  6.                 args = {MappedStatement.class, Object.class}
  7.         )})
  8. public class KeywordInterceptor implements Interceptor {
  9.     public DataSourceProperties getDataSourceProperties() {
  10.         return SpringContextUtil.getBean(DataSourceProperties.class);
  11.     }
  12.     private static final Logger logger = LoggerFactory.getLogger(KeywordInterceptor.class);
  13.     public static final String DATABASE_TYPE_DM = "dm";
  14.     public static final String DATABASE_TYPE_KINGBASE = "kingbase";
  15.     public static final String DATABASE_TYPE_GBASE = "gbase";
  16.     @Override
  17.     public Object intercept(Invocation invocation) throws Throwable {
  18.         logger.info("Intercepted target class: {}", invocation.getTarget().getClass().getName());
  19.         if (invocation.getTarget() instanceof Executor) {
  20.             MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
  21.             Object parameter = invocation.getArgs()[1];
  22.             BoundSql boundSql = mappedStatement.getBoundSql(parameter);
  23.             String originalSql = boundSql.getSql();
  24.             System.out.println("Original SQL: " + originalSql);
  25.             if (containsKeyword(originalSql, "关键字") || containsKeyword(originalSql, "关键字")) {
  26.                 String databaseId = mappedStatement.getDatabaseId();
  27.                 String currentDataSourceType;
  28.                 if (StringUtils.isNotEmpty(databaseId)) {
  29.                     currentDataSourceType = getCurrentDataSourceType(databaseId);
  30.                 } else {
  31.                     DataSourceProperties dataSourceProperties = getDataSourceProperties();
  32.                     String driverClassName = dataSourceProperties.getDriverClassName();
  33.                     currentDataSourceType = getCurrentDataSourceType(driverClassName);
  34.                 }
  35.                 SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
  36.                 String modifiedSql = modifySqlForDataSource(originalSql, currentDataSourceType, sqlCommandType);
  37.                 logger.info("Modified SQL: {}", modifiedSql);
  38.                 // 修改 SQL 语句(注意,这里是简化示例,实际情况可能需要更多处理)
  39.                 BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), modifiedSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
  40.                 // 复制其他字段
  41.                 copyBoundSqlFields(boundSql, newBoundSql);
  42.                 // 创建新的 MappedStatement 对象
  43.                 MappedStatement newMappedStatement = newMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
  44.                 // 替换原始的 MappedStatement 对象
  45.                 invocation.getArgs()[0] = newMappedStatement;
  46.                 return invocation.proceed();
  47.             } else {
  48.                 return invocation.proceed();
  49.             }
  50.             
  51.         } else {
  52.             return invocation.proceed();
  53.         }
  54.     }
  55.     private void copyBoundSqlFields(BoundSql source, BoundSql target) throws IllegalAccessException {
  56.         Field[] fields = BoundSql.class.getDeclaredFields();
  57.         for (Field field : fields) {
  58.             if (!field.getName().equals("sql")) {
  59.                 field.setAccessible(true);
  60.                 field.set(target, field.get(source));
  61.             }
  62.         }
  63.     }
  64.     private boolean containsKeyword(String sql, String keyword) {
  65.         // 使用正则表达式检查 SQL 中是否包含关键字
  66.         Matcher matcher = Pattern.compile("\\b" + keyword + "\\b", Pattern.CASE_INSENSITIVE).matcher(sql);
  67.         return matcher.find();
  68.     }
  69.     private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
  70.         MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
  71.         builder.resource(ms.getResource());
  72.         builder.fetchSize(ms.getFetchSize());
  73.         builder.statementType(ms.getStatementType());
  74.         builder.keyGenerator(ms.getKeyGenerator());
  75.         if (null != ms.getKeyProperties()) {
  76.             builder.keyProperty(String.join(",", ms.getKeyProperties()));
  77.         }
  78.         builder.timeout(ms.getTimeout());
  79.         builder.parameterMap(ms.getParameterMap());
  80.         builder.resultMaps(ms.getResultMaps());
  81.         builder.resultSetType(ms.getResultSetType());
  82.         builder.cache(ms.getCache());
  83.         builder.flushCacheRequired(ms.isFlushCacheRequired());
  84.         builder.useCache(ms.isUseCache());
  85.         return builder.build();
  86.     }
  87.     private static class BoundSqlSqlSource implements SqlSource {
  88.         private BoundSql boundSql;
  89.         public BoundSqlSqlSource(BoundSql boundSql) {
  90.             this.boundSql = boundSql;
  91.         }
  92.         @Override
  93.         public BoundSql getBoundSql(Object parameterObject) {
  94.             return boundSql;
  95.         }
  96.     }
  97.     private String getCurrentDataSourceType(String driverClassName) {
  98.         if (StringUtils.contains(driverClassName, DATABASE_TYPE_KINGBASE)) {
  99.             return DbType.KINGBASE_ES.getDb();
  100.         } else if (StringUtils.contains(driverClassName, DATABASE_TYPE_DM)) {
  101.             return DbType.DM.getDb();
  102.         } else if (StringUtils.contains(driverClassName, DATABASE_TYPE_GBASE)) {
  103.             return DbType.GBASE.getDb();
  104.         } else {
  105.             return DbType.MYSQL.getDb();
  106.         }
  107.     }
  108.     private String modifySqlForDataSource(String sql, String dataSourceType, SqlCommandType sqlCommandType){
  109.         if ("mysql".equalsIgnoreCase(dataSourceType)) {
  110.             return sql.replaceAll("\\b关键字\\b", "`关键字`");
  111.         } else {
  112.             if ("kingbasees".equalsIgnoreCase(dataSourceType)) {
  113.                 return sql.replaceAll("\\b关键字\\b", ""关键字"");
  114.             } else {
  115.                 if ("dm".equals(dataSourceType)) {
  116.                     return sql.replaceAll("\\b关键字\\b", ""关键字大写"");
  117.                 } else {
  118.                     return sql.replaceAll("\\b关键字\\b", ""关键字"");
  119.                 }
  120.             }
  121.         }
  122.     }
  123.     @Override
  124.     public Object plugin(Object target) {
  125.         return Plugin.wrap(target, this);
  126.     }
  127.     @Override
  128.     public void setProperties(Properties properties) {
  129.         // 可以通过配置文件传递参数
  130.     }
  131. }
复制代码
DataProperties类
  1. @Component
  2. @ConfigurationProperties(
  3.         prefix = "spring.datasource"
  4. )
  5. public class DataSourceProperties {
  6.     private String driverClassName;
  7.     private String url;
  8.     private String username;
  9.     private String password;
  10.     // Getters and Setters
  11.     public String getDriverClassName() {
  12.         return driverClassName;
  13.     }
  14.     public void setDriverClassName(String driverClassName) {
  15.         this.driverClassName = driverClassName;
  16.     }
  17. }
复制代码
Mybatis自动设置类
  1. @Configuration
  2. @EnableAutoConfiguration
  3. @MapperScan(value = "扫的类路径", annotationClass = Mapper.class, sqlSessionFactoryRef = "sqlSessionFactory")
  4. @MapperScan(value = "扫的类路径", annotationClass = Repository.class, sqlSessionFactoryRef = "sqlSessionFactory")
  5. public class DGMybatisAutoConfiguration {
  6.     @Autowired
  7.     private DataSourceProperties dataSourceProperties;
  8.     @Resource
  9.     private MultiTenantHandler multiTenantHandler;
  10.     public static final String DATABASE_TYPE_MYSQL = "mysql";
  11.     public static final String DATABASE_TYPE_DM = "dm";
  12.     public static final String DATABASE_TYPE_KINGBASE = "kingbase";
  13.     public static final String DATABASE_TYPE_GBASE = "gbase";
  14.     @Bean(destroyMethod = "")
  15.     public DruidDataSource dataSource() {
  16.         DruidDataSource druidDataSource = new DruidDataSource();
  17.         druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
  18.         druidDataSource.setUrl(dataSourceProperties.getUrl());
  19.         druidDataSource.setUsername(dataSourceProperties.getUsername());
  20.         druidDataSource.setPassword(dataSourceProperties.getPassword());
  21.         druidDataSource.setPoolPreparedStatements(true);
  22.         druidDataSource.setTestWhileIdle(true);
  23.         druidDataSource.setTestOnBorrow(true);
  24.         druidDataSource.setTestOnReturn(true);
  25.         druidDataSource.setKeepAlive(true);
  26.         druidDataSource.setMinIdle(5);
  27.         druidDataSource.setMaxActive(50);
  28.         druidDataSource.setMaxWait(60000);
  29.         druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
  30.         druidDataSource.setInitialSize(5);
  31.         druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
  32.         druidDataSource.setTimeBetweenConnectErrorMillis(60000);
  33.         druidDataSource.setMinEvictableIdleTimeMillis(300000);
  34.         druidDataSource.setValidationQueryTimeout(3);
  35.         //auto commit
  36.         druidDataSource.setDefaultAutoCommit(true);
  37.         return druidDataSource;
  38.     }
  39.     @Bean
  40.     public MybatisPlusInterceptor mybatisPlusInterceptor() {
  41.         MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
  42.         mybatisPlusInterceptor.addInnerInterceptor(new TenantLineInnerInterceptor(multiTenantHandler));
  43.         String driverClassName = dataSourceProperties.getDriverClassName();
  44.         // 分页插件
  45.         if (StringUtils.contains(driverClassName, DATABASE_TYPE_GBASE)) {
  46.             mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.GBASE));
  47.         } else if (StringUtils.contains(driverClassName, DATABASE_TYPE_DM)) {
  48.             mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.DM));
  49.         } else if (StringUtils.contains(driverClassName, DATABASE_TYPE_KINGBASE)) {
  50.             mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.KINGBASE_ES));
  51.         } else {
  52.             mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
  53.         }
  54.         return mybatisPlusInterceptor;
  55.     }
  56.     @Bean
  57.     public SqlSessionFactory sqlSessionFactory() throws Exception {
  58.         MybatisConfiguration configuration = new MybatisConfiguration();
  59.         configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
  60.         configuration.setMapUnderscoreToCamelCase(true);
  61.         configuration.setCacheEnabled(false);
  62.         configuration.setCallSettersOnNulls(true);
  63.         configuration.setJdbcTypeForNull(JdbcType.NULL);
  64.         configuration.addInterceptor(mybatisPlusInterceptor());
  65.         MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
  66.         sqlSessionFactoryBean.setConfiguration(configuration);
  67.         sqlSessionFactoryBean.setDataSource(dataSource());
  68.         GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
  69.         dbConfig.setIdType(IdType.AUTO);
  70.         GlobalConfig globalConfig = new GlobalConfig();
  71.         globalConfig.setDbConfig(dbConfig);
  72.         sqlSessionFactoryBean.setPlugins(new KeywordInterceptor());
  73.         return sqlSessionFactoryBean.getObject();
  74.     }
  75. }
复制代码
4. 总结

固然也可以使用Mybatis拦截器来做其他事变,比如数据加密脱敏,sql监控报警等功能,这也会额外产生一些性能开销,合理利用拦截器将会大大缩减开发本钱。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

tsx81429

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表