Mybatis-Plus code automatically generated

A simple example project, introduced the use of Mybatis -plus code automatic generation plug-in, according to the table structure to generate the corresponding class and XML configuration file

I. Code generation

The main content of this article is taken from the official tutorial, which provides an example of the code generation process

1. Prepare

Prepare two tables for testing

CREATE TABLE `userT0` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT ' ' COMMENT 'Username'.`pwd` varchar(26) NOT NULL DEFAULT ' ' COMMENT 'password'.`isDeleted` tinyint(1) NOT NULL DEFAULT '0'.`created` varchar(13) NOT NULL DEFAULT '0'.`updated` varchar(13) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `name` (`name`))ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `story_t0` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `userId` int(20) unsigned NOT NULL DEFAULT '0' COMMENT 'Author's userID'.`name` varchar(20) NOT NULL DEFAULT ' ' COMMENT 'Author name'.`title` varchar(26) NOT NULL DEFAULT ' ' COMMENT 'password'.`story` text COMMENT 'Story content'.`is_deleted` tinyint(1) NOT NULL DEFAULT '0'.`create_at` varchar(13) NOT NULL DEFAULT '0'.`update_at` varchar(13) NOT NULL DEFAULT '0'.`tag` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `userId` (`userId`))ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Copy the code

Note that the above two tables are named differently, either humped or underlined (mainly to illustrate the impact of different table names on generated code).

2. Configure dependencies

The first step is to add dependencies to our XML file

<dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> < version > 3.3.1. TMP < / version > < / dependency > < the dependency > < groupId > org. Freemarker < / groupId > <artifactId>freemarker</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <! The following two are used to test generated code. When generating code, > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> The < version > 3.2.0 < / version > < / dependency > < / dependencies >Copy the code

3. Code generation classes

Write code to generate class methods. The main logic is as follows

public class CodeGenerator {
    public static void main(String[] args) {
        // Code generator
        AutoGenerator mpg = new AutoGenerator();

        // Global configuration
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir") + "/spring-boot/106-mybatis-plus-generator";
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("YiHui");
        gc.setOpen(false);
        / / write are covered
        gc.setFileOverride(false);
        mpg.setGlobalConfig(gc);

        // Data source configuration
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("JDBC: mysql: / / 127.0.0.1:3306 / story? useUnicode=true&characterEncoding=UTF-8&useSSL=false");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("");
        mpg.setDataSource(dsc);

        / / package configuration
        PackageConfig pc = new PackageConfig();
        // No additional module is specified. If test is specified, the generated XML will be in mapper/test/
        pc.setModuleName("");
        pc.setParent("com.git.hui.boot.mybatis.plus");
        mpg.setPackageInfo(pc);

        // Custom configuration
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap(a) {
                // to do nothing}};// If the template engine is freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // Customize the output configuration
        List<FileOutConfig> focList = new ArrayList<>();
        // Custom configurations are printed first
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // Customize the output file name. If your Entity has a prefix or suffix, note that the XML name will change accordingly!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" +
                        tableInfo.getEntityName() + "Mapper"+ StringPool.DOT_XML; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);// Configure the template
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        // The controller class is not automatically generated
        templateConfig.setController(null);
        mpg.setTemplate(templateConfig);

        // Policy configuration
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        / / strategy. SetSuperEntityClass (" your parent entity, there is no need not set!" );
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // Public parent class
        / / strategy. SetSuperControllerClass (" your parent controller, no need not set up!" );
        // Public fields written in the parent class
        // strategy.setSuperEntityColumns("id");

        // Set the name of the table to be generated
        strategy.setInclude("userT0"."story_t0");
        strategy.setControllerMappingHyphenStyle(true);
        // strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(newFreemarkerTemplateEngine()); mpg.execute(); }}Copy the code

Most of the above code is generic, but the following highlights the points to be aware of

  • GlobalConfig#setOutputDir: Set the code output project root path, please specify according to the specific project requirements, do not include the package name oh
  • GlobalConfig#setFileOverride(true): set to true, each build overwrites the previously generated code, suitable for scenarios where the table structure changes
    • Note: This will cause the previously added business code to be overwritten, requiring extra attention
    • It is usually desirable to set it to false to intervene manually when the table structure changes
  • DataSourceConfig: data source Settings, which are related to mysql configuration
  • PackageConfig: the package information
    • setParent: Java package path
    • setModuleName: sets the module name, such as test, XML inmapper/test/Directory; The parent package is automatically added.test
  • FileOutConfig: XML file name
  • TemplateConfig: Template configuration
    • You can use default code generation templates, or you can use custom templates
    • If you don’t want to generate a template class, set it to NULL (no controller is generated above).
  • StrategyConfig: Policy configuration
    • You can specify mapping rules for DB -> POJO field names
    • POJO/Controller can be specified to inherit custom base classes

In IDEA, directly right-click the above code to generate the target class, as shown in the screenshot below

4. Output test

To test whether our generated class can operate on DB, it is necessary to write a startup class

@RestController
@SpringBootApplication
@MapperScan("com.git.hui.boot.mybatis.plus.mapper")
public class Application {
    @Autowired
    private IUserT0Service userT0Service;

    @GetMapping
    public UserT0 hello(int id) {
        return userT0Service.getById(id);
    }

    public static void main(String[] args) { SpringApplication.run(Application.class); }}Copy the code

Note the @mapperscan annotation above, followed by the corresponding application.yml configuration file

spring:
  datasource:
    # pay attention to the time zone
    url: JDBC: mysql: / / 127.0.0.1:3306 / story? useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password:

mybatis-plus:
  configuration:
    Log output of executed SQL statements
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code

Insert a piece of data into db

INSERT INTO `userT0` (`id`.`name`.`pwd`.`isDeleted`.`created`.`updated`)
VALUES
	(1.'A Grey'.'yihuihuiblog'.0.'the 2020-04-06 15'.'the 2020-04-06 15');
Copy the code

To access the url: http://localhost:8080/? id=1

The console output is as follows:

5. Description of special scenarios

The above code generation, for the first time to perform the generation code, the problem is not big; However, in the subsequent business development, there will always be some other situations, which are described below

A. Modify the table structure

GlobalConfig#setFileOverride(true) When the table structure changes, we need to regenerate the Entity.

B. Inherit public POJOs

We can define a generic PO class that we want all table-generated POJos to inherit from

@Data
public class BasePo implements Serializable {
    private static final long serialVersionUID = -1136173266983480386L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

}
Copy the code

Add the following two lines to the policy configuration for the code generated class

// All entity classes inherit from BasePo, and the id is in the parent class
StrategyConfig strategy = new StrategyConfig();
strategy.setSuperEntityClass(BasePo.class);
strategy.setSuperEntityColumns("id");
Copy the code

C. Generate some code

In some cases, IF I don’t want to generate service or XML, I might just need the entity class + mapper interface. In this case, I can set TemplateConfig

TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setController(null);
templateConfig.setEntityKt(null);
templateConfig.setService(null);
templateConfig.setServiceImpl(null);
Copy the code

II. The other

0. Project

Series of blog posts

  • 【DB series 】MybatisPlus Integration
  • 【DB series 】Mybatis+ annotations integration
  • 【DB series 】Mybatis+ XML integration

The source code

  • Project: github.com/liuyueyi/sp…
  • Source: github.com/liuyueyi/sp…

1. An ashy Blog

As far as the letter is not as good, the above content is purely one’s opinion, due to the limited personal ability, it is inevitable that there are omissions and mistakes, if you find bugs or have better suggestions, welcome criticism and correction, don’t hesitate to appreciate

Below a gray personal blog, record all the study and work of the blog, welcome everyone to go to stroll

  • A grey Blog Personal Blog blog.hhui.top
  • A Grey Blog-Spring feature Blog Spring.hhui.top