使用MybatisPlus的AutoGenerator生成代码
这个可自行官网查看,或者搜索引擎查一下一大堆可以参考的,这里就不过多叙述。
模版中能获取到哪些信息
官方没有给出在自定义模版中你能获取到哪些信息来生成你想要的代码,所以本人就看了一下源码,能获取到的信息都在com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine类的getObjectMap方法中,如下:
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
|
/** * <p> * 渲染对象 MAP 信息 * </p> * * @param tableInfo 表信息对象 * @return */ public Map<String, Object> getObjectMap(TableInfo tableInfo) { Map<String, Object> objectMap = new HashMap<>(); ConfigBuilder config = this .getConfigBuilder(); if (config.getStrategyConfig().isControllerMappingHyphenStyle()) { objectMap.put( "controllerMappingHyphenStyle" , config.getStrategyConfig().isControllerMappingHyphenStyle()); objectMap.put( "controllerMappingHyphen" , StringUtils.camelToHyphen(tableInfo.getEntityPath())); } objectMap.put( "restControllerStyle" , config.getStrategyConfig().isRestControllerStyle()); objectMap.put( "package" , config.getPackageInfo()); GlobalConfig globalConfig = config.getGlobalConfig(); objectMap.put( "author" , globalConfig.getAuthor()); objectMap.put( "idType" , globalConfig.getIdType() == null ? null : globalConfig.getIdType().toString()); objectMap.put( "logicDeleteFieldName" , config.getStrategyConfig().getLogicDeleteFieldName()); objectMap.put( "versionFieldName" , config.getStrategyConfig().getVersionFieldName()); objectMap.put( "activeRecord" , globalConfig.isActiveRecord()); objectMap.put( "kotlin" , globalConfig.isKotlin()); objectMap.put( "date" , new SimpleDateFormat( "yyyy-MM-dd" ).format( new Date())); objectMap.put( "table" , tableInfo); objectMap.put( "enableCache" , globalConfig.isEnableCache()); objectMap.put( "baseResultMap" , globalConfig.isBaseResultMap()); objectMap.put( "baseColumnList" , globalConfig.isBaseColumnList()); objectMap.put( "entity" , tableInfo.getEntityName()); objectMap.put( "entityColumnConstant" , config.getStrategyConfig().isEntityColumnConstant()); objectMap.put( "entityBuilderModel" , config.getStrategyConfig().isEntityBuilderModel()); objectMap.put( "entityLombokModel" , config.getStrategyConfig().isEntityLombokModel()); objectMap.put( "entityBooleanColumnRemoveIsPrefix" , config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix()); objectMap.put( "superEntityClass" , this .getSuperClassName(config.getSuperEntityClass())); objectMap.put( "superMapperClassPackage" , config.getSuperMapperClass()); objectMap.put( "superMapperClass" , this .getSuperClassName(config.getSuperMapperClass())); objectMap.put( "superServiceClassPackage" , config.getSuperServiceClass()); objectMap.put( "superServiceClass" , this .getSuperClassName(config.getSuperServiceClass())); objectMap.put( "superServiceImplClassPackage" , config.getSuperServiceImplClass()); objectMap.put( "superServiceImplClass" , this .getSuperClassName(config.getSuperServiceImplClass())); objectMap.put( "superControllerClassPackage" , config.getSuperControllerClass()); objectMap.put( "superControllerClass" , this .getSuperClassName(config.getSuperControllerClass())); return objectMap; } |
下面我就顺便整理一下方便以后查看
属性 | 类型 | 描述 | 示例 |
---|---|---|---|
controllerMappingHyphenStyle | boolean | controllerMapping是否为连字符形式 | 驼峰:@RequestMapping("/managerUserActionHistory")连字符:@RequestMapping("/manager-user-action-history") |
controllerMappingHyphen | String | 实体类的连字符形式 | manager-user-action-history |
restControllerStyle | boolean | 是否为RestController模式 | |
package | Map | 所有包配置信息 | |
package.Entity | String | Entity所在包路径 | com.geek.sean.test.model |
package.Mapper | String | Mapper所在包路径 | com.geek.sean.test.mapper |
package.Xml | String | Mapper的xml文件所在包路径 | com.geek.sean.test.mapper.xml |
package.ServiceImpl | String | Service实现类所在包路径 | com.geek.sean.test.service.impl |
package.Service | String | Service所在包路径 | com.geek.sean.test.service |
package.Controller | String | Controller所在包路径 | com.geek.sean.test.controller |
author | String | GlobalConfig中配置的author | |
idType | String | GlobalConfig中配置的idType | |
logicDeleteFieldName | String | 策略配置项中配置的逻辑删除属性名称 | |
versionFieldName | String | 策略配置项中配置的乐观锁属性名称 | |
activeRecord | boolean | 是否开启ActiveRecord模式 | |
kotlin | boolean | 是否开启 Kotlin 模式 | |
date | String | 当前日期(yyyy-MM-dd) | 2019-07-09 |
table | TableInfo | 表信息,关联到当前字段信息 | |
table.name | String | 表名 | 例:sys_user |
table.comment | String | 表描述 | 用户信息表 |
table.entityName | String | 实体类名称 | SysUser |
table.mapperName | String | Mapper类名 | SysUserMapper |
table.xmlName | String | Mapper对应的xml名称 | SysUserMapper |
table.serviceName | String | Service名称 | SysUserService |
table.serviceImplName | String | Service实现类名称 | SysUserServiceImpl |
table.controllerName | String | Controller名称 | SysUserController |
table.fields | List<TableField> | 字段信息集合 | |
table.fields[n].name | String | 字段名称 | user_id |
table.fields[n].type | String | 字段类型 | int(11)、varchar(64)、timestamp、char(1) |
table.fields[n].propertyName | String | 属性名 | userId、userName |
table.fields[n].columnType | String | 属性类型 | String、Integer |
table.fields[n].comment | String | 字段描述 | 用户名 |
table.importPackages | List<String> | 引入包集合 | [‘com.baomidou.mybatisplus.enums.IdType’,‘java.util.Date’] |
table.fieldNames | String | 表字段名,逗号分隔 | user_id, user_name, password |
enableCache | boolean | 是否在xml中添加二级缓存配置 | |
baseResultMap | boolean | 是否开启 BaseResultMap | |
baseColumnList | boolean | 是否开启 baseColumnList | |
entity | String | Entity类名 | |
entityColumnConstant | boolean | 【实体】是否生成字段常量(默认 false) | |
entityBuilderModel | boolean | 【实体】是否为构建者模型(默认 false) | |
entityLombokModel | boolean | 【实体】是否为lombok模型(默认 false) | |
entityBooleanColumnRemoveIsPrefix | boolean | Boolean类型字段是否移除is前缀(默认 false) | 比如 : 数据库字段名称 : ‘is_xxx’,类型为 : tinyint. 在映射实体的时候则会去掉is,在实体类中映射最终结果为 xxx |
superEntityClass | String | Entity父类 | BaseEntity |
superMapperClassPackage | String | Mapper父类包路径 | com.baomidou.mybatisplus.mapper.BaseMapper |
superMapperClass | String | Mapper父类 | BaseMapper |
superServiceClassPackage | String | Service父类包路径 | com.baomidou.mybatisplus.service.IService |
superServiceClass | String | Service父类 | IService |
superServiceImplClassPackage | String | Service实现类父类包路径 | com.baomidou.mybatisplus.service.impl.ServiceImpl |
superServiceImplClass | String | Service实现类父类 | ServiceImpl |
superControllerClassPackage | String | Controller类父类包路径 | |
superControllerClass | String | Controller父类 |
总结了一上午,个别字段没有放上,自己用到时候可以再去源码看看。
MybatisPlus遇到的坑
springBoot项目整合mybatis-plus、lombok时遇到了使用代码生成器生成实体类及mapper后,调用方法时报错找不到mapper,后经过一项项调整pom文件内jar包依赖,才知道mybatis-plus版本号存在很多不兼容。
1、导入依赖
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
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-jdbc</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-web</ artifactId > </ dependency > < dependency > < groupId >org.mybatis.spring.boot</ groupId > < artifactId >mybatis-spring-boot-starter</ artifactId > < version >2.0.1</ version > </ dependency > < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < scope >runtime</ scope > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-test</ artifactId > < scope >test</ scope > </ dependency > <!-- mybatis的orm插件 --> < dependency > < groupId >com.baomidou</ groupId > < artifactId >mybatis-plus</ artifactId > < version >2.1.9</ version > </ dependency > < dependency > < groupId >com.baomidou</ groupId > < artifactId >mybatisplus-spring-boot-starter</ artifactId > < version >1.0.4</ version > </ dependency > < dependency > < groupId >org.projectlombok</ groupId > < artifactId >lombok</ artifactId > < scope >provided</ scope > </ dependency > <!--阿里数据库链接依赖 --> < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > </ dependency > < dependency > < groupId >com.alibaba</ groupId > < artifactId >druid</ artifactId > < version >1.1.9</ version > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-configuration-processor</ artifactId > < optional >true</ optional > </ dependency > |
因为我用的是阿里云的数据库,所以需要导入阿里云及数据库依赖,lombok为简化实体类生成的插件jar包。
注意:千万注意mybatis-plus版本!!!千万注意mybatis-plus版本!!!千万注意mybatis-plus版本!!!
2、配置分页配置文件和数据源
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
|
package com.ds.tech.config; import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.alibaba.druid.pool.DruidDataSource; /** * 数据源配置 */ @Configuration public class DataSourceConfig { @Bean (name= "dataSource" ) @ConfigurationProperties (prefix= "spring.datasource" ) public DataSource dataSource(){ return new DruidDataSource(); } // 配置事物管理器 @Bean (name= "transactionManager" ) public DataSourceTransactionManager transactionManager(){ return new DataSourceTransactionManager(dataSource()); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.ds.tech.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.baomidou.mybatisplus.plugins.PaginationInterceptor; @Configuration //扫描dao或者是Mapper接口 @MapperScan ( "com.ds.tech.mapper*" ) public class MybatisPlusConfig { /** * mybatis-plus 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor(){ PaginationInterceptor page = new PaginationInterceptor(); page.setDialectType( "mysql" ); return page; } } |
配置代码生成器,然后就可以生成代码使用了
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
|
package com.ds.tech; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.rules.DbType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; /** * <p> * 代码生成器演示 * </p> */ public class MpGenerator { final static String dirPath = "D://mybatis" ; /** * <p> * MySQL 生成演示 * </p> */ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 选择 freemarker 引擎,默认 Veloctiy //mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(dirPath); gc.setAuthor( "dashen" ); gc.setFileOverride( true ); //是否覆盖 gc.setActiveRecord( false ); // 不需要ActiveRecord特性的请改为false gc.setEnableCache( false ); // XML 二级缓存 gc.setBaseResultMap( false ); // XML ResultMap gc.setBaseColumnList( false ); // XML columList // 自定义文件命名,注意 %s 会自动填充表实体属性! // gc.setMapperName("%sDao"); // gc.setXmlName("%sMapper"); // gc.setServiceName("MP%sService"); // gc.setServiceImplName("%sServiceDiy"); // gc.setControllerName("%sAction"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert( new MySqlTypeConvert(){ // 自定义数据库表字段类型转换【可选】 // @Override // public DbColumnType processTypeConvert(String fieldType) { // System.out.println("转换类型:" + fieldType); // // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。 // return super.processTypeConvert(fieldType); // } }); dsc.setDriverName( "com.mysql.jdbc.Driver" ); dsc.setUsername( "k" ); dsc.setPassword( "mj^" ); dsc.setUrl( "jdbc:mysql://rm-2zql.rds.aliyuncs.06/mjmk_dev?useUnicode=true&characterEncoding=utf-8" ); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 strategy.setTablePrefix( new String[] { "tb_" , "tsys_" }); // 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel); // 表名生成策略 strategy.setInclude( new String[] { "store" }); // 需要生成的表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 自定义实体父类 // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); // strategy.setSuperEntityClass("java.io.Serializable"); // 自定义实体,公共字段 // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); // 自定义 mapper 父类 // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper"); // 自定义 service 父类 // strategy.setSuperServiceClass("com.baomidou.demo.TestService"); // 自定义 service 实现类父类 // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); // 自定义 controller 父类 // strategy.setSuperControllerClass("com.baomidou.demo.TestController"); // 【实体】是否生成字段常量(默认 false) // public static final String ID = "test_id"; // strategy.setEntityColumnConstant(true); // 【实体】是否为构建者模型(默认 false) // public User setName(String name) {this.name = name; return this;} strategy.setEntityBuilderModel( true ); strategy.setEntityLombokModel( true ); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent( "com.ds.tech" ); // pc.setModuleName(""); pc.setController( "controller" ); pc.setEntity( "entity" ); pc.setMapper( "mapper" ); pc.setService( "service" ); pc.setServiceImpl( "serviceImpl" ); pc.setXml( "mapperXml" ); mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put( "abc" , this .getConfig().getGlobalConfig().getAuthor() + "-mp" ); this .setMap(map); } }; // 自定义 xxList.jsp 生成 List<FileOutConfig> focList = new ArrayList<FileOutConfig>(); /* focList.add(new FileOutConfig("/template/list.jsp.vm") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 return "D://my_" + tableInfo.getEntityName() + ".jsp"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);*/ // 调整 xml 生成目录演示 /* focList.add(new FileOutConfig("/templates/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { return dirPath + tableInfo.getEntityName() + "Mapper.xml"; } }); cfg.setFileOutConfigList(focList); */ mpg.setCfg(cfg); // 关闭默认 xml 生成,调整生成 至 根目录 /* TemplateConfig tc = new TemplateConfig(); tc.setXml(null); mpg.setTemplate(tc);*/ // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改, // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称 // TemplateConfig tc = new TemplateConfig(); // tc.setController("..."); // tc.setEntity("..."); // tc.setMapper("..."); // tc.setXml("..."); // tc.setService("..."); // tc.setServiceImpl("..."); // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。 // mpg.setTemplate(tc); // 执行生成 mpg.execute(); // 打印注入设置【可无】 System.err.println(mpg.getCfg().getMap().get( "abc" )); } } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/yyzc2/article/details/95166554