182°

Springboot整合Mybaits_Plus动态表名,简单的分表操作

 

需求是这样的,假如我参数里面多添加一个参数,suffix,用来区分表名后缀,比如article_1,article2,等等,MybaitsPlus实现

@Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
        dynamicTableNameParser.setTableNameHandlerMap(new HashMap<String, ITableNameHandler>(2) {{
            put("article", (metaObject, sql, tableName) -> {
                // metaObject 可以获取传入参数,这里实现你自己的动态规则
                String table =MybatisPlusConfig.getParamValue("suffix", metaObject);
                if(StringUtils.isNotEmpty(table)){
                    return tableName+"_"+table;
                }else{
                    return tableName;
                }
            });
        }});
        paginationInterceptor.setSqlParserList(Collections.singletonList(dynamicTableNameParser));
        return paginationInterceptor;
    }

 

private static String getParamValue(String title, MetaObject metaObject){
        //获取参数
        Object originalObject = metaObject.getOriginalObject();
        JSONObject originalObjectJSON = JSON.parseObject(JSON.toJSONString(originalObject));
        JSONObject boundSql = originalObjectJSON.getJSONObject("boundSql");
        JSONObject parameterObject = boundSql.getJSONObject("parameterObject");
        Object o = parameterObject.get(title);
        if(o !=null){
            return String.valueOf(o);
        }
        return null;
    }

 

 

全部评论: 0

    我有话说: