亲宝软件园·资讯

展开

mybatis plus 动态表名配置 mybatis plus 的动态表名的配置详解

团子是个傻子 人气:0
想了解mybatis plus 的动态表名的配置详解的相关内容吗,团子是个傻子在本文为您仔细讲解mybatis plus 动态表名配置的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:mybatis,plus,动态表名,下面大家一起来学习吧。

mybatis plus简介

详见mybatis plus的官网

业务要求

具体实现

MPConfig.java

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.parsers.DynamicTableNameParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: xuzz
 * @Description:
 * @Date: Created in 上午11:22 19-10-12
 * @Modified By:
 */
@Configuration
@MapperScan("com.dao")
public class MPConfig {

  @Autowired
  private Tables tableNames;

  /**
   * @Author: xuzz
   * @Date: 上午11:46 19-10-12
   * 动态表名
   */
  @Bean
  public PaginationInterceptor paginationInterceptor(){
    PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
    DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
    dynamicTableNameParser.setTableNameHandlerMap(new HashMap<String, ITableNameHandler>(2){{
      //涉及表集合
      List<String> tables = tableNames.getTableNames();
      //动态表规则 初始表名+_+code
      tables.forEach(tableTitle -> put(tableTitle,(metaObject, sql, tableName) -> tableName + "_" + String.valueOf(getParamValue("关键字段名",metaObject))));
    }});
    paginationInterceptor.setSqlParserList(Collections.singletonList(dynamicTableNameParser));
    return paginationInterceptor;
  }

  /**
   * @Author: xuzz
   * @Date: 下午2:55 19-10-12
   * 获取参数值
   */
  private Object 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");
     return parameterObject.get(title);
  }

Tables.java 表头列表类

@Configuration
@ConfigurationProperties("mp")
public class Tables {

  private List<String> tableNames;

  public List<String> getTableNames() {
    return tableNames;
  }

  public void setTableNames(List<String> tableNames) {
    this.tableNames = tableNames;
  }
}

application.yml

mp:
  tableNames: #表头列表
   - table1
   - table2
   - table3

其他基础配置的无异

加载全部内容

相关教程
猜你喜欢
用户评论