Automatic code generation based on springboot and mybatis plus


Automatic code generation based on springboot and mybatis plus

Originally, this chapter will introduce redis + AOP optimization permission, but we still need to introduce some mybatis plus automatic generation code first

Introduction to mybatis plus

Mybatis plus (opening new window) (MP) is an enhancement tool of mybatis (opening new window). Based on mybatis, it only makes enhancement without change, which is created to simplify development and improve efficiency.

Mybatis plus features

  • No invasion: only strengthen without change, the introduction of it will not have an impact on the existing project, as smooth as silk
  • Low loss: basic curd will be automatically injected at startup, with no performance loss and direct object-oriented operation
  • Powerful crud operation: built in general mapper and general service, most CRUD operations of single table can be realized with only a small amount of configuration, and more powerful condition constructor can meet all kinds of use requirements
  • Support lambda form call: through lambda expression, it is convenient to write all kinds of query conditions without worrying about wrong fields
  • Support automatic generation of primary key: support up to four primary key policies (including distributed unique ID generator – sequence), which can be freely configured to perfectly solve the primary key problem
  • Support activerecord mode: support activerecord form call, entity class only needs to inherit model class to perform powerful crud operation
  • Support custom global general operations: support global general method injection (write once, use anywhere)
  • Built in code generator: mapper, model, service and controller layer code can be generated quickly by using code or Maven plug-in. Template engine is supported, and there are more custom configurations for you to use
  • Built in paging plug-in: Based on mybatis physical paging, developers don’t need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary list query
  • The paging plug-in supports multiple databases: support mysql, MariaDB, Oracle, DB2, H2, hsql, SQLite, postgre, SQL server and other databases
  • Built in performance analysis plug-in: it can output SQL statement and its execution time. It is recommended to enable this function when developing and testing, which can quickly find out slow queries
  • Built in global interception plug-in: provide intelligent analysis blocking for delete and update operation of the whole table, and also customize interception rules to prevent misoperation

Mybatis plus support database

Any database that can crud with mybatis and support standard SQL

Frame structure

Automatic code generation based on springboot and mybatis plus

Mybatis plus code generator

Autogenerator is the code generator of mybatis plus. It can quickly generate the code of entity, mapper, mapper XML, service, controller and other modules, which greatly improves the development efficiency.

Using the tutorial

Add code generator dependency

`<! -- Lombok depends on -- >`
 `<! -- Integrated Druid connection pool -- >`
 `<! -- MySQL database driver -- >`
 `<! -- mybatis plus depends on -- >`
 `<! -- mybatis plus code generator -- >`
 `<! -- hutool Java toolkit -- >`
 `<! -- velocity template engine -- >`
 `<! -- swagger UI API document production tool -- >`

Add template engine dependency

Mybatis plus supports velocity (default), FreeMarker and Beetl. Users can choose the template engine they are familiar with. If none of them meet your requirements, you can use a custom template engine. This article uses default dependencies


Write configuration

Mybatis plus code generator provides a large number of user-defined parameters for users to choose, which can meet the needs of most people.

Configure globalconfig

Global policy globalconfig configuration


  • The output directory of the makefile
  • Default value: D disk root directory


  • Do you want to override the existing file
  • Default value: false


  • Open output directory
  • Default value: true


  • Add secondary cache configuration in XML
  • Default value: false


  • Developers
  • Default value: null


  • Open kotlin mode
  • Default value: false


  • Start swagger2 mode
  • Default value: false


  • Turn on activerecord mode
  • Default value: false


  • Open baseresultmap
  • Default value: false


  • Open basecolumnlist
  • Default value: false


  • Time type corresponding strategy
  • Default value: time\_ PACK

matters needing attention:

Configure% s as a placeholder as follows


  • Entity naming
  • Default value: null, for example: generate userentity from% sintity


  • Mapper naming
  • Default value: null, for example: generate userdao from% sdao


  • Mapper XML naming
  • Default value: null, for example: sdao build UserDao.xml


  • Service naming method
  • Default value: null, for example: generate userbusiness from% sbusiness


  • Service impl naming method
  • Default value: null. For example, generate userbusinessimpl from% sbusincimpl


  • Controller naming
  • Default value: null, for example, useraction generated by% saction


  • Specifies the ID type of the generated primary key
  • Default value: null
 `*Global configuration`
 `* @param projectPath`
 `* @return`
 `public static GlobalConfig initGlobal(String projectPath){`
 `GlobalConfig gc = new GlobalConfig();`
 `gc.setOutputDir(projectPath + "/src/main/java");`
 `return gc;`

Configure datasourceconfig


  • Database information query class
  • By default, the dbtype type determines the selection of the corresponding database. The built-in implementation of the idbquery interface can customize the database query, and the SQL statement can be customized to return the content you need


  • Database type
  • This class has built-in common database types


  • Database schema name
  • For example, PostgreSQL can be specified as publictypeConvert
  • Type conversion
  • By default, the dbtype decides to select the corresponding database built-in implementation to implement itypeconvert interface. The custom database field type is converted to the Java type you need. The built-in conversion type can not meet the requirement of realizing icolumntype interface customization


  • URL of the drive connectiondriverName
  • Driver nameusername
  • Database connection user namepassword
  • Database connection password
 `*Configure datasourceconfig`
 `* @return`
 `public  static DataSourceConfig initDataSource(){`
 `Props props = new Props("");`
 `DataSourceConfig dataSourceConfig = new DataSourceConfig();`
 `return dataSourceConfig;`

Package configuration package name configuration


  • Parent package name. If it is empty, all the sub package names must be written, otherwise, only the sub package names need to be written


  • Parent package module name


  • Entity package name


  • Service package name


  • Service impl package name


  • Mapper package name


  • Mapper XML package name


  • Controller package name


  • Path configuration information
 `*Package configuration`
 `* @param packname`
 `* @return`
 `public  static  PackageConfig initPackage(String packname){`
 `Props props = new Props("");`
 `PackageConfig packageConfig = new PackageConfig();`
 `return packageConfig;`

Template configuration


  • Java entity class template


  • Kotin entity class template


  • Service class template


  • Service impl implementation class template


  • Mapper template


  • Mapper XML template


  • Controller template
 `*Template configuration`
 `* @return`
 `public static TemplateConfig initTemplate() {`
 `TemplateConfig templateConfig = new TemplateConfig();`
 `//The controller, service and entity templates can be configured`
 `return templateConfig;`

Injectionconfig with custom attribute injection


  • Custom return configuration map object
  • The object can be passed to the template engine through quote


  • Custom output file
  • Configure fileoutconfig to specify the template file and output file to generate custom files


  • Define whether to create a file
  • Implement ifilecreate interface

This configuration is used to determine whether a class needs to be overridden. Of course, you can implement the merge file of the difference algorithm yourself


  • Inject custom map object (note that setmap should be put in)
 `*Custom attribute injection`
 `public static InjectionConfig initInjection(String projectPath, String moduleName) {`
 `//Custom configuration`
 `InjectionConfig injectionConfig = new InjectionConfig() {`
 `public void initMap() {`
 `//Can be used to customize properties`
 `//The template engine is velocity`
 `String templatePath = "/templates/mapper.xml.vm";`
 `//Custom output configuration`
 `List<FileOutConfig> focList = new ArrayList<>();`
 `//Custom configuration will be exported first`
 `focList.add(new FileOutConfig(templatePath) {`
 `public String outputFile(TableInfo tableInfo) {`
 `//Customize the output file name. If you set the Prefix suffix for entity, please note that the XML name will change!! `
 `return projectPath + "/src/main/resources/mapper/" + moduleName`
 `+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;`
 `return injectionConfig;`

Policy configuration strategyconfig

 `*Policy configuration`
 `public static StrategyConfig initStrategy(String[] tableNames) {`
 `StrategyConfig strategyConfig = new StrategyConfig();`
 `//The wildcard mode can be enabled when the table name is marked with an *`
 `if (tableNames.length == 1 && tableNames[0].contains("*")) {`
 `String[] likeStr = tableNames[0].split("_");`
 `String likePrefix = likeStr[0] + "_";`
 `strategyConfig.setLikeTable(new LikeTable(likePrefix));`
 `} else {`
 `return strategyConfig;`

Code generator

`public static void main(String[] args) {`
 `String projectPath = System.getProperty("user.dir");`
 `String modulename = scanner ("module name")`
 `String [] tablenames = scanner ("table name, separated by multiple commas"). Split (",")`
 `//Code generator`
 `AutoGenerator autoGenerator = new AutoGenerator();`
 `autoGenerator.setCfg(initInjection(projectPath, moduleName));`
 `autoGenerator.setTemplateEngine(new VelocityTemplateEngine());`

Read console content

 `* <p>`
 `*Read console content`
 `* </p>`
 `public static String scanner(String tip) {`
 `Scanner scanner = new Scanner(;`
 `StringBuilder help = new StringBuilder();`
 ` help.append ("please input" + tip + ":")`
 `if (scanner.hasNext()) {`
 `String ipt =;`
 `if (StrUtil.isNotEmpty(ipt)) {`
 `return ipt;`
 `Throw new mybatisplus exception ("please enter the correct" + tip + "! ");`

to configure


Run the code

Automatic code generation based on springboot and mybatis plus


Enter XX at the time of input indication\_ *For all tables with XX prefix, if the full name is entered, the corresponding table will be generated

official account…