Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use mybatis-plus to reverse automatically generate classes in SpringBoot projects

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to use mybatis-plus reverse automatic generation of classes in SpringBoot projects", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "how to use mybatis-plus reverse automatic generation classes in SpringBoot projects"!

Catalogue

1. Create a new sub-module project under your SpringBoot project

two。 Create a new package and a java class name under this module: CodeGenerator

3. Create a new folder under resources to store mapper files

4. Configure the CodeGenerator class

5. Start the code generation class main method

6. Delete a file

1. Create a new sub-module project under your SpringBoot project

Pom.xml adds the following dependencies:

1.8 mysql mysql-connector-java com.baomidou mybatis-plus-generator 3.3.2 com.baomidou mybatis-plus-extension 3.3.2 org.projectlombok Lombok true org.springframework.boot spring-boot-starter-freemarker 2.3.1.RELEASE org.springframework.boot spring-boot-maven-plugin

Ps: the name is random. You'd better bring generator to tell that this is an automatic code generation module.

two。 Create a new package and a java class name under this module: CodeGenerator

The complete code is as follows:

Import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;import com.baomidou.mybatisplus.core.toolkit.StringPool;import com.baomidou.mybatisplus.core.toolkit.StringUtils;import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.InjectionConfig;import com.baomidou.mybatisplus.generator.config.*;import com.baomidou.mybatisplus.generator.config.po.TableInfo;import com.baomidou.mybatisplus.generator.config.rules.DateType;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine Import java.util.ArrayList;import java.util.List;import java.util.Scanner;/** * @ Description: code generation class * / public class CodeGenerator {/ / database connection parameter public static String driver = "com.mysql.cj.jdbc.Driver"; public static String url = "jdbc:mysql://localhost:3306/rht_test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true"; public static String username= "root"; public static String password= "123456" / / parent-level package name public static String parentPackage = "cn.rht"; / / the target path for code generation public static String generateTo = "/ rht-generator/src/main/java"; / / the generation path of mapper.xml public static String mapperXmlPath = "/ rht-generator/src/main/resources/mapper"; / / the common base class of the controller, which is used to abstract the controller's public method. A null value indicates that there is no parent class public static String baseControllerClassName. / / the common base class of the business layer, used to abstract the public method public static String baseServiceClassName; / / author name public static String author = "rht.cn"; / / module name, which is used to make up the template file of the package name public static String modelName = "portal"; / / Mapper interface, without writing the suffix .ftl public static String mapperTempalte = "/ ftl/mapper.java"; / *

* read 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.isNotEmpty (ipt)) {return ipt;}} throw new MybatisPlusException ("Please enter correct" + tip + "!") ;} / * RUN THIS * / public static void main (String [] args) {/ / Code generator AutoGenerator mpg = new AutoGenerator (); / / Global configuration GlobalConfig gc = new GlobalConfig (); String projectPath = System.getProperty ("user.dir"); gc.setOutputDir (projectPath + generateTo); gc.setAuthor (author) Gc.setOpen (false); / / set time type to Date gc.setDateType (DateType.TIME_PACK); / / enable swagger / / gc.setSwagger2 (true); / / set resultMap gc.setBaseResultMap (true) of mapper.xml; mpg.setGlobalConfig (gc); / / data source configuration DataSourceConfig dsc = new DataSourceConfig (); dsc.setUrl (url) / / dsc.setSchemaName ("public"); dsc.setDriverName (driver); dsc.setUsername (username); dsc.setPassword (password); mpg.setDataSource (dsc); / / package configuration PackageConfig pc = new PackageConfig (); pc.setEntity ("model"); / / pc.setModuleName (scanner ("module name")); pc.setModuleName (modelName) Pc.setParent (parentPackage); mpg.setPackageInfo (pc); / / Custom configuration InjectionConfig cfg = new InjectionConfig () {@ Override public void initMap () {/ / to do nothing}}; List focList = new ArrayList () FocList.add (new FileOutConfig ("/ templates/mapper.xml.ftl") {@ Override public String outputFile (TableInfo tableInfo) {/ / Custom input file name return projectPath + mapperXmlPath + "/" + tableInfo.getEntityName () + "Mapper" + StringPool.DOT_XML;}}) Cfg.setFileOutConfigList (focList); mpg.setCfg (cfg); mpg.setTemplate (new TemplateConfig (). SetXml (null)); mpg.setTemplate (new TemplateConfig (). SetMapper (mapperTempalte)); / / Policy configuration StrategyConfig strategy = new StrategyConfig (); strategy.setNaming (NamingStrategy.underline_to_camel); / / Field Hump naming strategy.setColumnNaming (NamingStrategy.underline_to_camel) / / set the lombok strategy.setEntityLombokModel (true) of the entity class; / / set the parent class if (baseController ClassNameplate null) strategy.setSuperControllerClass (baseControllerClassName) of the controller; / / set the parent class if (baseServiceClassName! = null) strategy.setSuperServiceImplClass (baseServiceClassName) of the service class; / / strategy. / / set the annotation strategy.setEntityTableFieldAnnotationEnable (true) of the attribute of the entity class corresponding to the table field; / / set the table name String tableName = scanner ("table name, all all tables"); if (! "all" .equals IgnoreCase (tableName) {strategy.setInclude (tableName);} strategy.setTablePrefix (pc.getModuleName () + "_"); strategy.setRestControllerStyle (true); mpg.setStrategy (strategy); / / Select the freemarker engine to be specified as follows, note that pom dependencies must have! Mpg.setTemplateEngine (new FreemarkerTemplateEngine ()); mpg.execute ();}} 3. Create a new folder under resources to store mapper files

Create a new template file: mapper.java.ftl

The complete code of the template is as follows:

Package ${package.Mapper}; import ${package.Entity}. ${entity}; import ${superMapperClassPackage}; import org.springframework.stereotype.Repository;/** *

* ${table.comment!} Mapper interface *

* * @ author ${author} * @ since ${date} * / interface ${table.mapperName}: ${superMapperClass} @ Repositorypublic interface ${table.mapperName} extends ${superMapperClass} {} 4 Configure the CodeGenerator class

Ps: please configure it according to your actual path

5. Start the code generation class main method

Ps: entering all will automatically generate all configuration files under the configuration database, or directly enter a single table name to generate the Controller,mapper,service,model layer and mapper.xml file of a table

The following is a display of some of the automatically generated file information in my input table: user

User entity class

UserMapper.xml file

If you have a lot of tables to generate, but don't want to generate all of them, you can use 134 lines of code in the CodeGenerator class code

/ / set table name String tableName = scanner ("table name, all all tables"); if (! "all" .equals IgnoreCase (tableName)) {strategy.setInclude (tableName);}

To be replaced by:

String [] tableNames = {"user", "dept"}; / / Collection of database table names for (int I = 0; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report