欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-22 13:22:24
mybatis plus简介详见业务要求 业务上要求存储数据的时候根据某个字段动态的选择数据要存储的表. 如根据code字段: code->[1001,1002]来进行选择存储的表: 经过...

mybatis plus简介

详见

业务要求

  • 业务上要求存储数据的时候根据某个字段动态的选择数据要存储的表.
  • 如根据code字段: code->[1001,1002]来进行选择存储的表:
  • 经过下面的配置实现动态表名如 --> table1_1001,table_1002的效果.以此动态生成表名的效果.

具体实现

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

其他基础配置的无异

到此这篇关于mybatis plus 的动态表名的配置详解的文章就介绍到这了,更多相关mybatis plus 动态表名配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!