[TOC]

1, the preface

As the saying goes: to do a good job, you must sharpen your tools.

When we start our springBoot development projects, we will definitely manually create Contoller, entity,

, Service, ServiceImpl, Mapper, and even XML files. Manual efficiency is slow.

Here is how to use a code generator to automatically generate the code for each module.

MyBatis-Plus code generator, through the AutoGenerator can quickly generate Entity, Mapper, Mapper XML, Service, Controller and other modules of the code, greatly improve the development efficiency.

Effect preview:

Code review

package com.scaffold.test.base;

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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CodeGenerator {
    /** * 

* read the 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)) { returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!"); } 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 + "/src/main/java"); gc.setAuthor("alex wong"); gc.setOpen(false); // Set the name gc.setControllerName("%sController"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setMapperName("%sMapper"); / / set the resultMap gc.setBaseResultMap(true); gc.setBaseColumnList(true); // gc.setFileOverride(true); // gc.setSwagger2(true); Entity attribute Swagger2 annotation mpg.setGlobalConfig(gc); // Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/test? useUnicode=true&useSSL=false&characterEncoding=utf8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("admin"); dsc.setPassword("Your mysql password"); mpg.setDataSource(dsc); // Custom configuration InjectionConfig cfg = new InjectionConfig() { @Override public void initMap(a) { // to do nothing}};/ / package configuration PackageConfig pc = new PackageConfig(); // pc.setModulename (scanner(" module name ")); pc.setParent("com.scaffold.test"); mpg.setPackageInfo(pc); // If the template engine is Velocity String templatePath = "/templates/mapper.xml.vm"; // 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); mpg.setTemplate(templateConfig); // Policy configuration StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // Public fields written in the parent class // strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("Table name, separated by multiple Commas").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(newVelocityTemplateEngine()); mpg.execute(); ,}}Copy the code

2. Install dependencies

I will not say more about the initial Spring Boot project, but can refer to the following:

Introduction of spring-boot-starter, spring-boot-starter-test, mybatis-plus-boot-starter, Lombok, mysql-connector dependencies:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <! -- Lombok simplified code -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <! -- Mybatis -- plus launcher -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2 rainfall distribution on 10-12</version>
        </dependency>

        <! -- mysql jdbc -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <! -- Generator -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2 rainfall distribution on 10-12</version>
        </dependency>

  			<! -- Generator default version dependency -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>


    </dependencies>
Copy the code

3, configuration,

Add the mysql database configuration to the application.yml configuration file

server:
  port: 9002

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: JDBC: mysql: / / 127.0.0.1:3306 / test
    username: admin
    password: * * * * * * * * * * * *

logging:
  level:
    root: warn
    com.scaffold.test.mapper: trace

Copy the code

4. Generator code

New com. Scaffold. Test. Base. CodeGenerator class

package com.scaffold.test.base;

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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CodeGenerator {
    /** * 

* read the 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)) { returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!"); } 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 + "/src/main/java"); gc.setAuthor("alex wong"); gc.setOpen(false); // Set the name gc.setControllerName("%sController"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setMapperName("%sMapper"); / / set the resultMap gc.setBaseResultMap(true); gc.setBaseColumnList(true); // gc.setFileOverride(true); // gc.setSwagger2(true); Entity attribute Swagger2 annotation mpg.setGlobalConfig(gc); // Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/test? useUnicode=true&useSSL=false&characterEncoding=utf8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("admin"); dsc.setPassword("* * * * * * * * * *"); mpg.setDataSource(dsc); // Custom configuration InjectionConfig cfg = new InjectionConfig() { @Override public void initMap(a) { // to do nothing}};/ / package configuration PackageConfig pc = new PackageConfig(); // pc.setModulename (scanner(" module name ")); pc.setParent("com.scaffold.test"); mpg.setPackageInfo(pc); // If the template engine is Velocity String templatePath = "/templates/mapper.xml.vm"; // 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); mpg.setTemplate(templateConfig); // Policy configuration StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // Public fields written in the parent class // strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("Table name, separated by multiple Commas").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(newVelocityTemplateEngine()); mpg.execute(); }}Copy the code

Step 1: Modify to your data source

Step 2: Modify the package

Step 3: Execute the main method

The table name entered here must be a real table in your database, otherwise it will not take effect;

5. Code presentation

Take the job table as an example:

jobController

package com.scaffold.test.controller;


import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/** ** <p> * Front-end controller * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
@RestController
@RequestMapping("/job")
public class JobController {}Copy the code

Job Entity Entity class

package com.scaffold.test.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>
 * 
 * </p>
 *
 * @author alex wong
 * @sinceThe 2020-06-14 * /
@Data
@EqualsAndHashCode(callSuper = false)
public class Job implements Serializable {

    private static final long serialVersionUID=1L;

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

    private String name;

    private Integer age;

    private String position;


}

Copy the code

Job mapper

package com.scaffold.test.mapper;

import com.scaffold.test.entity.Job;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/** * <p> * Mapper interface * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
public interface JobMapper extends BaseMapper<Job> {}Copy the code

Job Service Indicates the Service interface

package com.scaffold.test.service;

import com.scaffold.test.entity.Job;
import com.baomidou.mybatisplus.extension.service.IService;

/** * <p> * Service class * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
public interface JobService extends IService<Job> {}Copy the code

Job ServiceImpl Indicates the implementation method of the service class

package com.scaffold.test.service.impl;

import com.scaffold.test.entity.Job;
import com.scaffold.test.mapper.JobMapper;
import com.scaffold.test.service.JobService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/** * <p> * Service implementation class * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper.Job> implements JobService {}Copy the code

Mapper XML

<?xml version="1.0" encoding="UTF-8"? >

      
<mapper namespace="com.scaffold.test.mapper.JobMapper">

    <! -- Query mapping result -->
    <resultMap id="BaseResultMap" type="com.scaffold.test.entity.Job">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="age" property="age" />
        <result column="position" property="position" />
    </resultMap>

    <! -- Generic query result column -->
    <sql id="Base_Column_List">
        id, name, age, position
    </sql>

</mapper>

Copy the code

6. Code testing

We still use the job table as an example, although the single table operation, generally not Mapper XML, can use Mybatis- Plus CRUD, but we will still use XML to do database operations.

6.1 Adding a Job

Add SQL statement Mapper/jobmapper.xml

<insert id="insertJob">
        insert into job
        (name, age, position)
        values
        (#{name}, #{age}, #{position})
    </insert>
Copy the code

2, com. Scaffold. Test. Mapper. JobMapper

package com.scaffold.test.mapper;

import com.scaffold.test.entity.Job;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;

/** * <p> * Mapper interface * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
public interface JobMapper extends BaseMapper<Job> {

    public void insertJob(Job job);

}

Copy the code

3. Add Service interface and implementation method

The Service interface: com. Scaffold. Test. Service. The JobService

package com.scaffold.test.service;

import com.scaffold.test.entity.Job;
import com.baomidou.mybatisplus.extension.service.IService;

/** * <p> * Service class * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
public interface JobService extends IService<Job> {

    public String addJob(Job job);

}

Copy the code

JobServiceImpl interface implementation methods: com. Scaffold. Test. Service. Impl. JobServiceImpl

package com.scaffold.test.service.impl;

import com.scaffold.test.entity.Job;
import com.scaffold.test.mapper.JobMapper;
import com.scaffold.test.service.JobService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/** * <p> * Service implementation class * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper.Job> implements JobService {

    @Autowired
    private JobMapper jobMapper;

    @Override
    public String addJob(Job job) {
        jobMapper.insertJob(job);
        return "Added successfully"; }}Copy the code

JobController control layer: com. Scaffold. Test. Controller. JobController

package com.scaffold.test.controller;


import com.scaffold.test.entity.Job;
import com.scaffold.test.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/** ** <p> * Front-end controller * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
@RestController
@RequestMapping("/job")
public class JobController {

    @Autowired
    private JobService jobService;

    @PostMapping("/add")
    public String add(a){
        Job job = new Job();
        job.setAge(20);
        job.setPosition("General manager");
        job.setName("Wang wang");
        returnjobService.addJob(job); }}Copy the code

The result is as follows:

Test success;

6.2 Other Operations

Other add, delete, change and check operations are not repeated:

The code is as follows:

src/main/resources/mapper/JobMapper.xml

<?xml version="1.0" encoding="UTF-8"? >

      
<mapper namespace="com.scaffold.test.mapper.JobMapper">

    <! -- Query mapping result -->
    <resultMap id="BaseResultMap" type="com.scaffold.test.entity.Job">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="position" property="position"/>
    </resultMap>

    <! -- Generic query result column -->
    <sql id="Base_Column_List">
        id, name, age, position
    </sql>

    <insert id="insertJob">
        insert into job
        (name, age, position)
        values
        (#{name}, #{age}, #{position})
    </insert>

    <select id="selectAll" resultMap="BaseResultMap">
        select * from job
    </select>

    <update id="updateJob">
        update job set
        name = #{name},
        age = #{age},
        position = #{position}
    </update>

    <delete id="deleteJobById">
        delete from job
        where id = #{id}
    </delete>

</mapper>

Copy the code

com.scaffold.test.mapper.JobMapper

package com.scaffold.test.mapper;

import com.scaffold.test.entity.Job;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import java.util.List;

/** * <p> * Mapper interface * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
public interface JobMapper extends BaseMapper<Job> {

    public void insertJob(Job job);

    public List<Job> selectAll(a);

    public void updateJob(Job job);

    public void deleteJobById(int id);

}

Copy the code

com.scaffold.test.service.JobService

package com.scaffold.test.service;

import com.scaffold.test.entity.Job;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/** * <p> * Service class * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
public interface JobService extends IService<Job> {

    public String addJob(Job job);

    public List<Job> findAll(a);

    public String updateJob(Job job);

    public String deleteJobById(int id);

}

Copy the code

com.scaffold.test.service.impl.JobServiceImpl

package com.scaffold.test.service.impl;

import com.scaffold.test.entity.Job;
import com.scaffold.test.mapper.JobMapper;
import com.scaffold.test.service.JobService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/** * <p> * Service implementation class * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper.Job> implements JobService {

    @Autowired
    private JobMapper jobMapper;

    @Override
    public String addJob(Job job) {
        jobMapper.insertJob(job);
        return "Added successfully";
    }

    @Override
    public List<Job> findAll(a) {
        return jobMapper.selectAll();
    }

    @Override
    public String updateJob(Job job) {
        jobMapper.updateJob(job);
        return "Update successful";
    }

    @Override
    public String deleteJobById(int id) {
        jobMapper.deleteJobById(id);
        return "Deleted successfully"; }}Copy the code

com.scaffold.test.controller.JobController

package com.scaffold.test.controller;


import com.scaffold.test.entity.Job;
import com.scaffold.test.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** ** <p> * Front-end controller * </p> **@author alex wong
 * @sinceThe 2020-06-14 * /
@RestController
@RequestMapping("/job")
public class JobController {

    @Autowired
    private JobService jobService;

    / / add
    @PostMapping("/add")
    public String add(a) {
        Job job = new Job();
        job.setAge(20);
        job.setPosition("General manager");
        job.setName("Wang wang");
        return jobService.addJob(job);
    }

    // Query all
    @GetMapping("/list")
    public List<Job> getList(a) {
        return jobService.findAll();
    }

    / / update
    @PostMapping("/update")
    public String update(a) {
        Job job = new Job();
        job.setAge(20);
        // Wang wang is demoted
        job.setPosition("General Manager Assistant");
        job.setName("Wang wang");
        return jobService.updateJob(job);
    }

    / / delete
    @PostMapping("/delete")
    public String delete(@RequestParam int id) {
        // Woof is removed
        returnjobService.deleteJobById(id); }}Copy the code