Newer
Older
newfiber-data-adapter / src / main / java / org / springnewfiber / dataadapter / config / MybatisPlusConfig.java
package org.springnewfiber.dataadapter.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springnewfiber.dataadapter.xf.XfDataEnum;
import org.springnewfiber.dataadapter.xf.mapper.DataAccessRecordMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Configuration
public class MybatisPlusConfig {

    static List<String> tableList(){
        List<String> tables = new ArrayList<>();
//        for (XfDataEnum value : XfDataEnum.values()) {
//            String tableName="t_data_access_record".concat("_").concat(value.getCode());
//            tables.add(tableName);
//        }
        tables.add("t_data_access_record");
        return tables;
    }
    @Autowired
    @Lazy
    private DataAccessRecordMapper dataAccessRecordMapper;
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor paginationInterceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameParser = new DynamicTableNameInnerInterceptor();
        dynamicTableNameParser.setTableNameHandlerMap(new HashMap<String, TableNameHandler>(XfDataEnum.values().length) {{
            //metaObject 元对象 ;sql 执行的SQL ;tableName 表名
            //这里put的key就是需要替换的原始表名,也就是实体类的表名
            //这里的tableName就是我们定义的动态表名变量,
            for (String table : tableList()) {
                put(table, (sql, tableName) -> {
                    // 获取传入参数 tableName,tableName的值就是替换后的表名
                  String newTable=RequestDataHelper.getRequestData(table);
                  //判断表是否存在
                  if (newTable!=null){
                     int count= dataAccessRecordMapper.selectTableExists(newTable);
                      if(count==0){
                          dataAccessRecordMapper.createTable(newTable);
                      }
                      return newTable;
                }
                 return table;
                });
            }
        }});
        paginationInterceptor.addInnerInterceptor(dynamicTableNameParser);
        return paginationInterceptor;
    }
    }