SpringBoot combined with MyBatis Plus to automatically generate code
Originally, this chapter wanted to introduce Redis+AOP optimization permissions, but I still need to introduce some MyBatis Plus automatic generation code first.
Introduction to MyBatis Plus
MyBatis-Plus (opens new window) (MP for short) is an enhancement tool for MyBatis (opens new window). On the basis of MyBatis, only enhancements are made without changes. It is born to simplify development and improve efficiency.
MyBatis Plus features
- No intrusion: only make enhancements without making changes, the introduction of it will not affect the existing project, it is as smooth as silk
- Low loss: basic CURD will be automatically injected at startup, performance is basically no loss, direct object-oriented operation
- Powerful CRUD operations: built-in general Mapper, general service, only a small amount of configuration can realize most of the CRUD operations of a single table, and a more powerful condition builder to meet various usage requirements
- Support Lambda form call: through Lambda expressions, it is convenient to write various query conditions, no need to worry about writing wrong fields
- Supports automatic generation of primary keys: supports up to 4 primary key strategies (contains a distributed unique ID generator-Sequence), which can be freely configured to perfectly solve primary key problems
- Support ActiveRecord mode: Support ActiveRecord form call, entity classes only need to inherit Model class to perform powerful CRUD operations
- Support custom global general operations: support global general method injection (Write once, use anywhere)
- Built-in code generator: Use code or Maven plug-in to quickly generate Mapper, Model, Service, Controller layer code, support template engine, and more custom configurations for you to use
- Built-in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query
- Paging plug-in supports multiple databases: supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
- Built-in performance analysis plug-in: Sql statement and its execution time can be output. It is recommended to enable this function during development and testing to quickly detect slow queries
- Built-in global interception plug-in: Provides full table delete and update operation intelligent analysis and blocking, and can also customize interception rules to prevent misoperation
MyBatis Plus support database
Any database that can use mybatis for crud and supports standard sql
Framework
MyBatis Plus code generator
AutoGenerator is the code generator of MyBatis-Plus. Through AutoGenerator, you can quickly generate the code of Entity, Mapper, Mapper XML, Service, Controller and other modules, which greatly improves the development efficiency.
Use tutorial
Add code generator dependency
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--集成druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--Mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<!--MyBatis Plus 依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!--MyBatis Plus 代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<!--Hutool Java工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.7</version>
</dependency>
<!--Velocity模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--Swagger-UI API文档生产工具-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
Add template engine dependency
MyBatis-Plus supports Velocity (default), Freemarker, Beetl, and users can choose a template engine that they are familiar with. If it does not meet your requirements, you can use a custom template engine. This article uses default dependencies
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
Write configuration
The MyBatis-Plus code generator provides a large number of custom parameters for users to choose, which can meet the needs of most people.
Configure GlobalConfig
Global policy globalConfig configuration
outputDir
- Output directory of generated files
- Default value: D
disk root directory fileOverride - Whether to overwrite existing files
- Default value: false
open - Whether to open the output directory
- Default value: true
enableCache - Whether to add secondary cache configuration in xml
- Default value: false
author - Developer
- Default value: null
kotlin - Turn on Kotlin mode
- Default value: false
swagger2 - Open swagger2 mode
- Default value: false
activeRecord - Enable ActiveRecord mode
- Default value: false
baseResultMap - Open BaseResultMap
- Default value: false
baseColumnList - Open baseColumnList
- Default value: false
dateType - Time type corresponding strategy
- Default value: TIME_PACK
Notes:
Configure %s as a placeholder as follows
entityName
- Entity naming
- Default value: null For example: %sEntity generates UserEntity
mapperName - mapper naming method
- Default value: null For example: %sDao generates UserDao
xmlName - Mapper xml naming method
- Default value: null For example: %sDao generates UserDao.xml
serviceName - Service naming method
- Default value: null For example: %sBusiness generates UserBusiness
serviceImplName - service impl naming method
- Default value: null For example: %sBusinessImpl generates UserBusinessImpl
controllerName - Controller naming method
- Default value: null For example: %sAction generates UserAction
idType - Specify the ID type of the generated primary key
- Default value: null
/**
* 全局配置
* @param projectPath
* @return
*/
public static GlobalConfig initGlobal(String projectPath){
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("zbb");
gc.setOpen(false);
gc.setSwagger2(true);
gc.setBaseResultMap(true);
gc.setFileOverride(true);
gc.setDateType(DateType.ONLY_DATE);
gc.setEntityName("%s");
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
return gc;
}
Configure DataSourceConfig
dbQuery
- Database information query
- The default type is determined by selecting the corresponding database dbType built to achieve the realization IDbQuery custom interfaces customized database query SQL statement returns the content they need
dbType - Database type
- This class has built-in commonly used database types [Required]
schemaName - Database schema name
- For example, PostgreSQL can be specified as publictypeConvert
- Type conversion
- The default is determined by the dbType type. Choose the corresponding database built-in implementation to implement the ITypeConvert interface. The custom database field type is converted to the java type you need. The built-in conversion type cannot meet the requirements. The IColumnType interface custom
url can be implemented. - URLdriverName of the driver connection
- Driver name username
- Database connection username password
- Database connection password
/**
*
* 配置 DataSourceConfig
* @return
*/
public static DataSourceConfig initDataSource(){
Props props = new Props("application.properties");
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setUrl(props.getStr("dataSource.url"));
dataSourceConfig.setDriverName(props.getStr("dataSource.driverName"));
dataSourceConfig.setUsername(props.getStr("dataSource.username"));
dataSourceConfig.setPassword(props.getStr("dataSource.password"));
return dataSourceConfig;
}
Package configuration package name configuration
parent
- Parent package name. If it is empty, the following sub-package name must be written all, otherwise, only the sub-package name
moduleName - Parent package module name
entity - Entity package name
service - Service package name
serviceImpl - Service Impl package name
mapper - Mapper package name
xml - Mapper XML package name
controller - Controller package name
pathInfo - Path configuration information
/**
* 包配置
* @param packname
* @return
*/
public static PackageConfig initPackage(String packname){
Props props = new Props("application.properties");
PackageConfig packageConfig = new PackageConfig();
packageConfig.setModuleName(packname);
packageConfig.setParent(props.getStr("package.base"));
packageConfig.setEntity("model");
return packageConfig;
}
Template configuration TemplateConfig
entity
- Java entity class template
entityKt - Kotin entity class template
service - Service class template
serviceImpl - Service impl implementation class template
mapper - mapper template
xml - mapper xml template
controller - controller controller template
/**
* 模板配置
* @return
*/
public static TemplateConfig initTemplate() {
TemplateConfig templateConfig = new TemplateConfig();
//可以对controller、service、entity模板进行配置
templateConfig.setXml(null);
return templateConfig;
}
Custom attribute injection into InjectionConfig
map
- Custom return configuration Map object
- The object can be passed to the template engine by cfg.xxx reference
fileOutConfigList - Custom output file
- Configure FileOutConfig to specify template files and output files to achieve the purpose of custom file generation
fileCreate - Customize whether to create a file
- Implement the IFileCreate interface
This configuration is used to determine whether a certain class needs to be overwritten and created. Of course, you can implement the merge file of the difference algorithm by yourself
initMap
- Inject a custom Map object (note that you need to put it in setMap)
/**
* 自定义属性注入
*/
public static InjectionConfig initInjection(String projectPath, String moduleName) {
// 自定义配置
InjectionConfig injectionConfig = new InjectionConfig() {
@Override
public void initMap() {
// 可用于自定义属性
}
};
// 模板引擎是Velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + moduleName
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
injectionConfig.setFileOutConfigList(focList);
return injectionConfig;
}
Strategy Configuration StrategyConfig
/**
* 策略配置
*/
public static StrategyConfig initStrategy(String[] tableNames) {
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
strategyConfig.setEntityLombokModel(true);
strategyConfig.setRestControllerStyle(true);
//当表名中带*号时可以启用通配符模式
if (tableNames.length == 1 && tableNames[0].contains("*")) {
String[] likeStr = tableNames[0].split("_");
String likePrefix = likeStr[0] + "_";
strategyConfig.setLikeTable(new LikeTable(likePrefix));
} else {
strategyConfig.setInclude(tableNames);
}
return strategyConfig;
}
Code generator
public static void main(String[] args) {
String projectPath = System.getProperty("user.dir");
String moduleName = scanner("模块名");
String[] tableNames = scanner("表名,多个英文逗号分割").split(",");
// 代码生成器
AutoGenerator autoGenerator = new AutoGenerator();
autoGenerator.setGlobalConfig(initGlobal(projectPath));
autoGenerator.setDataSource(initDataSource());
autoGenerator.setPackageInfo(initPackage(moduleName));
autoGenerator.setCfg(initInjection(projectPath, moduleName));
autoGenerator.setTemplate(initTemplate());
autoGenerator.setStrategy(initStrategy(tableNames));
autoGenerator.setTemplateEngine(new VelocityTemplateEngine());
autoGenerator.execute();
}
Read console content
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StrUtil.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
Configure application.properties
dataSource.url=jdbc:mysql://db:3306/mymes?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
dataSource.driverName=com.mysql.jdbc.Driver
dataSource.username=reader
dataSource.password=123456
package.base=com.springboot.mymes_demo.modules
Run code
Note:
Enter xx_* when inputting to indicate all tables with xx prefix. If the full name is entered, the corresponding table will be generated
the public
Official account https://mp.weixin.qq.com/s/nfat2WWWUXdmfUGFBAVEuA