Automatic code generation based on springboot and mybatis plus

Time:2021-3-4

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 -- >`
 `<dependency>`
 `<groupId>org.projectlombok</groupId>`
 `<artifactId>lombok</artifactId>`
 `<optional>true</optional>`
 `</dependency>`
 `<! -- Integrated Druid connection pool -- >`
 `<dependency>`
 `<groupId>com.alibaba</groupId>`
 `<artifactId>druid-spring-boot-starter</artifactId>`
 `<version>1.1.10</version>`
 `</dependency>`
 `<! -- MySQL database driver -- >`
 `<dependency>`
 `<groupId>mysql</groupId>`
 `<artifactId>mysql-connector-java</artifactId>`
 `<version>5.1.10</version>`
 `</dependency>`
 `<! -- mybatis plus depends on -- >`
 `<dependency>`
 `<groupId>com.baomidou</groupId>`
 `<artifactId>mybatis-plus-boot-starter</artifactId>`
 `<version>3.3.2</version>`
 `</dependency>`
 `<! -- mybatis plus code generator -- >`
 `<dependency>`
 `<groupId>com.baomidou</groupId>`
 `<artifactId>mybatis-plus-generator</artifactId>`
 `<version>3.3.2</version>`
 `</dependency>`
 `<! -- hutool Java toolkit -- >`
 `<dependency>`
 `<groupId>cn.hutool</groupId>`
 `<artifactId>hutool-all</artifactId>`
 `<version>4.5.7</version>`
 `</dependency>`
 `<! -- velocity template engine -- >`
 `<dependency>`
 `<groupId>org.apache.velocity</groupId>`
 `<artifactId>velocity-engine-core</artifactId>`
 `<version>2.2</version>`
 `</dependency>`
 `<! -- swagger UI API document production tool -- >`
 `<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 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

`<dependency>`
 `<groupId>org.apache.velocity</groupId>`
 `<artifactId>velocity-engine-core</artifactId>`
 `<version>2.2</version>`
`</dependency>`

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

outputDir

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

fileOverride

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

open

  • Open output directory
  • Default value: true

enableCache

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

author

  • Developers
  • Default value: null

kotlin

  • Open kotlin mode
  • Default value: false

swagger2

  • Start swagger2 mode
  • Default value: false

activeRecord

  • Turn on 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

matters needing attention:

Configure% s as a placeholder as follows

entityName

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

mapperName

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

xmlName

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

serviceName

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

serviceImplName

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

controllerName

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

idType

  • 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");`
 `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 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

dbType

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

schemaName

  • 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

  • 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("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, all the sub package names must be written, otherwise, only the sub package names need to be written

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
`/**`
 `*Package configuration`
 `* @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

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 template
`/**`
 `*Template configuration`
 `* @return`
 `*/`
 `public static TemplateConfig initTemplate() {`
 `TemplateConfig templateConfig = new TemplateConfig();`
 `//The controller, service and entity templates can be configured`
 `templateConfig.setXml(null);`
 `return templateConfig;`
 `}`

Injectionconfig with custom attribute injection

map

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

fileOutConfigList

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

fileCreate

  • 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

initMap

  • 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() {`
 `@Override`
 `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) {`
 `@Override`
 `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;`
 `}`
 `});`
 `injectionConfig.setFileOutConfigList(focList);`
 `return injectionConfig;`
 `}`

Policy configuration strategyconfig

`/**`
 `*Policy configuration`
 `*/`
 `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);`
 `//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 {`
 `strategyConfig.setInclude(tableNames);`
 `}`
 `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.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>`
 `*Read console content`
 `* </p>`
 `*/`
 `public static String scanner(String tip) {`
 `Scanner scanner = new Scanner(System.in);`
 `StringBuilder help = new StringBuilder();`
 ` help.append ("please input" + tip + ":")`
 `System.out.println(help.toString());`
 `if (scanner.hasNext()) {`
 `String ipt = scanner.next();`
 `if (StrUtil.isNotEmpty(ipt)) {`
 `return ipt;`
 `}`
 `}`
 `Throw new mybatisplus exception ("please enter the correct" + tip + "! ");`
 `}`

to 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 the code

Automatic code generation based on springboot and mybatis plus

Note:

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 accounthttps://mp.weixin.qq.com/s/nf…