mybatis plus简介
业务要求
- 业务上要求存储数据的时候根据某个字段动态的选择数据要存储的表.
- 如根据code字段: code->[1001,1002]来进行选择存储的表:
- 经过下面的配置实现动态表名如 --> table1_1001,table_1002的效果.以此动态生成表名的效果.
具体实现
MPConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
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 表头列表类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@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
1
2
3
4
5
|
mp: tableNames: #表头列表 - table1 - table2 - table3 |
其他基础配置的无异
到此这篇关于mybatis plus 的动态表名的配置详解的文章就介绍到这了,更多相关mybatis plus 动态表名配置内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/XuZZ94/article/details/102547671