This article is the seventh in a series of articles.
- Integration of SpringBoot quickly start to add, delete, change and check
- MybatisPlus part 2 – Application and summary of conditional builders
- MybatisPlus 3 – Custom SQL
- Table pagination and drop-down page query
- MybatisPlus chapter 5 -Active Record mode introduction
- MybatisPlus 6 – Primary key generation strategy in detail
The basic implementation principle of code generator
Most developers have used or heard of the “template engine”, which allows us to separate views from data, quickly develop view pages, and integrate template results for display in the browser. Its core implementation principle is: HTML template page + page data = output results. The process of page view output is implemented through the template engine.
The code generator implementation is almost identical to the template engine implementation of page rendering logic, except for the following differences:
- The so-called template: is the code of a language + template engine syntax placeholder, which is used for data conversion. So the code generator template file no longer refers to an HTML page template file, but can be any type of code file.
- The output of the template engine is output to the browser for page rendering in the project, but for the code generator, the output of the template engine is saved to a disk file.
How to write a template file
To write a template file, we first need to know how normal code would be written. For example, the following POJO code:
The POJO code above, written as a Freemarker template file, looks like this:
package ${package.Entity}; <#list table.importPackages as pkg> import ${pkg}; </#list> <#if entityLombokModel> import lombok.Data; import lombok.EqualsAndHashCode; </#if> /** * <p> * ${table.comment! } * </p> * * @author ${author} * @since ${date} */ <#if entityLombokModel> @Data <#if superEntityClass?? > @EqualsAndHashCode(callSuper = true) <#else> @EqualsAndHashCode(callSuper = false) </#if> </#if> public class ${entity} extends Model<${entity}> { <#list table.fields as field> private ${field.propertyType} ${field.propertyName}; </#list>Copy the code
Mybatis Plus code generated template file: gitee.com/baomidou/my…
Where does the data come from?
With a template file, we want to generate code through a template engine, and the next question is where does the data come from? We have the data to generate the code
- From the configuration, such as the package path, which is static and doesn’t change very often, the package path where the code generated by a project is stored usually doesn’t change very often.
- From the database, such as: entity class name, entity class field name, entity class field type information. Similar to reverse engineering, entity information is generated from database table names, field names, field types, and so on.
3.1. Obtain the INFORMATION_SCHEMA information of MySQL as an example
Our code auto-generation is for database operations, so we need to understand the structure of the database tables first
SELECT column_name,data_type,is_nullable,character_maximum_length,column_comment
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name='kpi_task'
AND table_schema='home'
ORDER BY ordinal_positionCopy the code
SQL > select kPI_task from home;
- Column_name can be used as a table field to generate the name of an entity class’s member variable parameter (usually a hump identifier rule)
- Data_type, IS_NULlable, character_MAXIMum_length can be used to generate verification rules.
- Comments can be used to generate column_COMMENT
Use of Mybatis Plus code generator
If you understand the code generator implementation above, you should understand the configuration below as well.
4.1. Add dependencies
- Add code generator dependencies
< the dependency > < groupId > com. Baomidou < / groupId > < artifactId > mybatis - plus - generator < / artifactId > < version > 3.3.2 rainfall distribution on 10-12 < / version > </dependency>Copy the code
-
MyBatis-Plus supports Velocity (default), Freemarker, Beetl, and users can choose the template engine they are familiar with.
Velocity (default) :
< the dependency > < groupId > org. Apache. Velocity < / groupId > < artifactId > velocity - engine - core < / artifactId > < version > 2.2 < / version > </dependency>Copy the code
A Freemarker:
< the dependency > < groupId > org. Freemarker < / groupId > < artifactId > freemarker < / artifactId > < version > 2.3.30 < / version > </dependency>Copy the code
Beetl:
<dependency> <groupId>com.ibeetl</groupId> <artifactId> <version>3.1.8.RELEASE</version> </dependency>Copy the code
Attention! If you choose a non-default engine, you need to set up the template engine in AutoGenerator.
AutoGenerator generator = new AutoGenerator();
// set freemarker engine
generator.setTemplateEngine(new FreemarkerTemplateEngine());
// set beetl engine
generator.setTemplateEngine(new BeetlTemplateEngine());
// set custom engine (reference class is your custom engine class)
generator.setTemplateEngine(new CustomTemplateEngine());
// other config
...Copy the code
4.2. Code generation configuration
AutoGenerator is the code generator of MyBatis-Plus, through which the code of Entity, Mapper, Mapper XML, Service, Controller and other modules can be generated quickly. Greatly improved the development efficiency.
By executing the following test case, Mybatis Plus can help us achieve the above layers of code generation to the corresponding package path
Public class CodeGenerator {@test public void startGenerator() {//1, GlobalConfig config = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); Config.setactiverecord (true)// Enable AR mode. SetAuthor ("zimug")// Set author.setOutputDir (projectPath +) SetFileOverride (true)// The second generation overrides the first one. SetOpen (true)// Whether to open the output directory automatically after the generation is complete //.setidType (idtype.auto)// Primary key policy .setServicename ("%sService")// Whether the generated service interface name starts with I, SetBaseResultMap (true)// Generate resultmap.setBasecolumnList (true); DataSourceConfig = new DataSourceConfig(); DataSourceConfig. SetDbType (DbType. MYSQL) / / database type setDriverName (". Com. MYSQL. JDBC Driver ") .setUrl("jdbc:mysql://localhost:3306/zimug") .setUsername("root") .setPassword("zimug3456"); //3, StrategyConfig = new StrategyConfig(); StrategyConfig. SetCapitalMode (true). / / open global capital named setNaming (NamingStrategy. Underline_to_camel) / / table name is mapped to the entity naming strategy (underscore to hump) // Table field mapping attribute name policy (unspecified naming).setColumnNaming(namingStrategy.underline_to_camel)//.settablePrefix ("tb_")// table name prefix //.setSuperEntityClass(" Your own superclass entity, no need to set!") ) //.setSuperEntityColumns("id"); / / write in public field in the parent class. / / setSuperControllerClass (" inherited the custom Controller as the full name of the package name, no need not set!" ).setrestControllerStyle (true)// Generate @restController controller.setentitylombokModel (true)// Use Lombok .setInclude("sys_user","sys_role"); PackageConfig PackageConfig = new PackageConfig(); Packageconfig.setparent ("com.zimug.example")// Set the package name to parent.setmapper ("mapper").setService("service") .setController("controller") .setEntity("entity") .setXml("mapper"); AutoGenerator = new AutoGenerator(); AutoGenerator = new AutoGenerator(); autoGenerator.setGlobalConfig(config) .setDataSource(dataSourceConfig) .setStrategy(strategyConfig) .setPackageInfo(packageConfig); Execute autogenerator.execute (); }}Copy the code
Welcome to my blog, where there are many fine collections
- This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.
Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.
- Spring Boot2.0 by Hand
- Spring Security- JWT-OAUTH2
- RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
- “Actual SpringCloud Micro-service from Bronze to King”
- VUE Series