preface
C: Once you’re a programmer, you’ll find that you can’t see things that are repetitive, especially when you’re writing code.
“Trouble! So write work efficiency is too low!”
“Why all this redundant code? Isn’t it a good idea to bring it up?”
.
Jokingly, the ultimate goal of a programmer was to “replace your peers, please yourself, and the company will replace you.”
A variety of automation or generation tools have been created to “please” themselves (to simplify a lot of repetitive work), and code generators are the most typical for solving repetitive code problems.
This article, The teacher will mainly take you to know MP code generator.
Introduction to the
The purpose of MP is to simplify MyBatis, but some parts are still repetitive after simplification. In this case, a code generator provided by MP: AutoGenerator can be used to solve the problem.
The AutoGenerator can quickly generate the code of Entity, Mapper, Mapper XML, Service, Controller and other modules, greatly improving the development efficiency. [1]
Using the step
In order to test the MP code generator, remember to back up the previous project in advance so that we can clean up the original project code and use the MP code generator to generate the previous database code.
Add the dependent
MP removed the default dependencies for code generators and template engines after 3.0.3 [1], so when we use code generators, we need to add these two dependencies first.
<! -- Code generator dependencies -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1 track</version>
</dependency>
<! -- Template engine dependencies -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
Copy the code
Freemarker is the template engine of choice, which is a well-known template technology of Apache open source.
MP also supports Velocity (the default) and Beetl, so you can choose your own familiar templating engine, or use a custom templating engine if you are not satisfied with either. [1]
Creating an entry class
Once the dependencies are added and a generator entry class is created, MP’s code generator can be used.
/** * MyBatis Plus code generator entry class * execute main method console input module table name press Enter automatically generate the corresponding project directory **@author Charles7c
* @since2021/1/28 * /
public class CodeGenerator {
public static void main(String[] args) {}}Copy the code
Write the configuration
The MP code generator provides a large number of custom configuration parameters for users to choose from, which can meet the needs of most people [1]. Next, we configure the generator in the main method.
Step 1: Initialize the code generator.
// Create a code generator object
AutoGenerator generator = new AutoGenerator();
// Specify the template engine as FreeMarker, which is not required if you use the default engine, Velocity
generator.setTemplateEngine(new FreemarkerTemplateEngine());
Copy the code
Step 2: Specify global configuration.
// Create a global configuration object
GlobalConfig globalConfig = new GlobalConfig();
// Specify the output directory of the generated file.
// system.getProperty ("user.dir") retrieves the absolute path to the current project
// Output directory example: D: IdeaProjects\mybatis-plus-demo\ SRC \main\ Java
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
// Specify the developer
globalConfig.setAuthor("Charles7c");
// Specifies whether to open the output directory
globalConfig.setOpen(false);
// Specify the global configuration
generator.setGlobalConfig(globalConfig);
Copy the code
Step 3: Specify the package name configuration by which you specify the package path to generate code.
// Create a package configuration object
PackageConfig packageConfig = new PackageConfig();
// Specify the parent package name
packageConfig.setParent("com.example");
// Specify the package name configuration
generator.setPackageInfo(packageConfig);
Copy the code
Teacher zha said: only specify the parent package name can be, MP specified a good child package name. The default package name for the entity class is Entity, and the default package name for the business class is service….
Step 4: Specify the data source configuration by which you specify the specific database for which you want to generate code.
// Create a data source configuration object
DataSourceConfig dataSourceConfig = new DataSourceConfig();
// Specify data source information
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mybatisplus_demodb? serverTimezone=Asia/Shanghai&useUnicode=true&useSSL=false&characterEncoding=utf8");
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("root");
// Specify the data source configuration
generator.setDataSource(dataSourceConfig);
Copy the code
Step 5: Specify the policy configuration, through which you can specify which tables to generate or exclude.
// Create a policy configuration object
StrategyConfig strategyConfig = new StrategyConfig();
// Specify the naming strategy for database tables to map to entities
// Underline_to_camel
// Output no_change unchanged
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
// Specify the naming strategy for mapping database table fields to entities
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
// Specifies whether the entity class uses Lombok annotations
strategyConfig.setEntityLombokModel(true);
// Specify whether the generated Controller class is annotated with @RestController
// Default false: @controller -> true: @restController
strategyConfig.setRestControllerStyle(true);
// Specify the policy configuration
generator.setStrategy(strategyConfig);
Copy the code
Step 6: Perform the build.
// Perform the build
generator.execute();
Copy the code
Test generation
Modular generation
The above method is to generate all of the database tables directly, but when our project is modular split, we can create the specified form for the specified module.
An example of a project database table with a split module is as follows:
Let’s also simulate by renaming the database table to sys_user.
Then, we changed step 3 to add the module name Settings.
// Create a package configuration object
PackageConfig packageConfig = new PackageConfig();
// Specify the parent package name
packageConfig.setParent("com.example");
// Specify the module name of the parent package, for example, user module user, role module role...
// If input modules are split, each module has its own set of controllers, services, daOs...
packageConfig.setModuleName(scanner("Module name"));
// Specify the package name configuration
generator.setPackageInfo(packageConfig);
Copy the code
Add the table Settings for code generation and table prefix removal Settings in step 5.
// Create a policy configuration object
StrategyConfig strategyConfig = new StrategyConfig();
// Specify the naming strategy for database tables to map to entities
// Underline_to_camel
// Output no_change unchanged
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
// Specify the naming strategy for mapping database table fields to entities
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
// Specifies whether the entity class uses Lombok annotations
strategyConfig.setEntityLombokModel(true);
// Specify whether the generated Controller class is annotated with @RestController
// Default false: @controller -> true: @restController
strategyConfig.setRestControllerStyle(true);
// Specify the name of the table to include, allowing regular expressions (optional with exclude)
strategyConfig.setInclude(scanner("Table name, separated by multiple Commas").split(","));
// Specify the table prefix to remove
// If the table is divided by module, for example, the user table of the system module is sys_user, then the table prefix to remove is sys_
strategyConfig.setTablePrefix(packageConfig.getModuleName() + "_");
// Specify the policy configuration
generator.setStrategy(strategyConfig);
Copy the code
To make typing easier, we can define a scanner method for dynamic typing.
/** * * read the console contents *
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("Please enter" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!");
}
Copy the code
Let’s test it out.
You can also use setSuperXXClass(Class) to set custom parent classes for Enity, Service, Controller, etc., so that the generated code will inherit the specified Class directly. For example, the setSuperEntityClass() method can specify the parent class of an Entity, so that auditing class information does not have to be a copy of each Entity class, and data populating Settings are easier.
The resources
[1]MyBatis Plus code generator: baomidou.com/guide/gener…
Afterword.
C: Finally, the complete code generator configuration code for this article is attached below. For more configuration, you can go to the code generator section of MP official website. In fact, all code generators are the same idea, template + data + template engine. Some time later, Mr. Cha will also write a post on common code generator implementations so that you can “please” yourself.
// Demo example, execute main method console input module table name press enter automatically generated corresponding project directory
public class CodeGenerator {
/** * Read the console contents */
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("Please enter" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!");
}
public static void main(String[] args) {
Initialize the code generator
// Create a code generator object
AutoGenerator generator = new AutoGenerator();
// Specify the template engine as FreeMarker, which is not required if you use the default engine, Velocity
generator.setTemplateEngine(new FreemarkerTemplateEngine());
// 2. Specify the global configuration
// Create a global configuration object
GlobalConfig globalConfig = new GlobalConfig();
// Specify the output directory of the generated file.
// system.getProperty ("user.dir") retrieves the absolute path to the current project
// Output directory example: D: IdeaProjects\mybatis-plus-demo\ SRC \main\ Java
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
// Specify the developer
globalConfig.setAuthor("Charles7c");
// Specifies whether to open the output directory
globalConfig.setOpen(false);
// Specify the global configuration
generator.setGlobalConfig(globalConfig);
// 3. Specify the package name
// Create a package configuration object
PackageConfig packageConfig = new PackageConfig();
// Specify the parent package name
packageConfig.setParent("com.example");
// Specify the module name of the parent package, for example, user module user, role module role...
// If input modules are split, each module has its own set of controllers, services, daOs...
packageConfig.setModuleName(scanner("Module name"));
// Specify the package name configuration
generator.setPackageInfo(packageConfig);
// 4. Specify the data source configuration
// Create a data source configuration object
DataSourceConfig dataSourceConfig = new DataSourceConfig();
// Specify data source information
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mybatisplus_demodb? serverTimezone=Asia/Shanghai&useUnicode=true&useSSL=false&characterEncoding=utf8");
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("root");
// Specify the data source configuration
generator.setDataSource(dataSourceConfig);
// 5. Specify policy configuration
// Create a policy configuration object
StrategyConfig strategyConfig = new StrategyConfig();
// Specify the naming strategy for database tables to map to entities
// Underline_to_camel
// Output no_change unchanged
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
// Specify the naming strategy for mapping database table fields to entities
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
// Specifies whether the entity class uses Lombok annotations
strategyConfig.setEntityLombokModel(true);
// Specify whether the generated Controller class is annotated with @RestController
// Default false: @controller -> true: @restController
strategyConfig.setRestControllerStyle(true);
// Specify the name of the table to include, allowing regular expressions (optional with exclude)
strategyConfig.setInclude(scanner("Table name, separated by multiple Commas").split(","));
// Specify the table prefix to remove
// If the table is divided by module, for example, the user table of the system module is sys_user, then the table prefix to remove is sys_
strategyConfig.setTablePrefix(packageConfig.getModuleName() + "_");
// Specify the policy configuration
generator.setStrategy(strategyConfig);
// Perform the buildgenerator.execute(); }}Copy the code
Teacher Zha said: For the learning of technology, teacher Zha has always followed the following steps: With a simple demo to let it run first, and then learn it the most commonly used API and configuration can let yourself up, finally, on the basis of proficiency in the spare time reading the source to try to make myself to be able to see clearly its running mechanism, part of the cause of the problem, at the same time, draw lessons from these technology to enhance your own code level.
So in the teacher’s article, the early basic are small white, only interspersed with a very small amount of source research. Of course, such as the small white update, you still like, the late will not regularly dedicated to part of the technology of the source code analysis.