“Offer comes, ask friends to take it! I am participating in the 2022 Spring Recruit Punch card campaign. Click here for more details.”

MyBatis Plus and MyBatis code generator comparison

  • MPG provides a large number of custom Settings, and the generated code can meet all types of requirements
  • Table name and field naming policy selection
    • MyBatis Plus dbColumnUnderline configuration is enabled by default. MPG recommends the use of hump naming, so that fields can directly correspond to entity classes and entity class attributes without mapping, which can avoid the loss of mapping performance. Use underscores to enable the hump conversion rule
  • MPG can generate Entity classes, Mapper interfaces, Mapper mapping files, Service layers, and Controller layers
  • MBG can generate Entity classes, Mapper interfaces, and Mapper mapping files

For MyBatis code generator MBG, please refer to Data Access MyBatis (7) – MBG & PageHelper

MyBatis Plus code generator MPG

Engineering structures,

Create Maven project mybatis-plus-mpg with IDEA MyBatis Plus (MyBatis Plus) – BaseMapper CRUD (Part A) Created in the Mybatis -plus project.

In addition to the dependencies mentioned above, there are MyBatis Plus code generator dependencies and template engine dependencies to run MPG. MPG uses Apache’s Velocity template by default, while the Freemarker template engine is used.

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1 track of</version>
</dependency>
<! -- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>
Copy the code

Since MPG generates the Controller layer, Spring Web MVC dependencies need to be added

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring-version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring-version}</version>
</dependency>
Copy the code

MPG generator code

public class GeneratorApp {

    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=tr ue";
    private static final String JDBC_USERNAME = "root";
    private static final String JDBC_PASSWORD = "root";
    // Code generator
    @Test
    public void generator(a){

        FastAutoGenerator.create(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD)
                .globalConfig(builder -> {
                    builder.author("Jingnan") // Set the author
                            EnableSwagger () // enableSwagger mode
                            .fileOverride() // Overwrite the generated file
                            .outputDir("src/main/java"); // Specify the output directory
                })
                .packageConfig(builder -> {
                    builder.parent("com") // Set the parent package name
                            .moduleName("lilith") // Set the module name of the parent package
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "src/main/resources/mappers/")); // Set the mapperXml generation path
                })
                .strategyConfig(builder -> {
                    builder.addInclude("t_tesla").addInclude("porsche") // Set the name of the table to be generated
                            .addTablePrefix("t_"."c_"); // Set the filter table prefix
                })
                .templateEngine(new FreemarkerTemplateEngine()) // Use the Freemarker engine template, which defaults to the Velocity engine template.execute(); }}Copy the code

The code in the generator method is copied from the MyBatis Plus website with only the database connection information and package name information modified

Run the generator method

Based on the log output from the console, you can see that code generation is complete

Viewing the directory Structure

MPG automatically generates the Controller layer, service layer, Mapper interface, and Mapper XML file

If you want to generate multiple tables at once, you can simply addInclude(“porsche”)

See the MyBatis Plus code generator for more configurations

Test MPG generated code

Test TeslaMapper

Create TeslaMapperTest to test the TeslaMapper interface

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class TeslaMapperTest {

    @Resource
    private TeslaMapper teslaMapper;

    @Test
    public void insert(a){
        Tesla tesla = new Tesla();
        tesla.setName("Model 3P 2022");
        tesla.setVehicleType("Four-door sedan");
        tesla.setPrice(270000.00);
        tesla.setFactory("Tesla Gigafactory in Shanghai");

        int count = teslaMapper.insert(tesla);
        System.out.println("Number of rows updated after INSERT:" + count);
    }

    @Test
    public void selectById(a){
        Tesla tesla = teslaMapper.selectById(6);
        System.out.println(SELECT * from (SELECT * from (SELECT * from)); + tesla);
    }

    @Test
    public void update(a){
        Tesla tesla = new Tesla();
        tesla.setId(1166057516);
        tesla.setFactory("The Tesla Gigafactory in Berlin.");

        int count = teslaMapper.updateById(tesla);
        System.out.println("Number of rows updated after UPDATE:" + count);
    }

    @Test
    public void delete(a){
        int count = teslaMapper.deleteById(1166057516);
        System.out.println("Number of lines updated after DELTE operation:"+ count); }}Copy the code

Execute insert method

Execute the selectById method

Execute the udpdate method

Execute delete method

Test ITeslaService

Create a new ITeslaService test class, ITeslaServiceTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class ITeslaServiceTest {

    @Resource
    private ITeslaService teslaService;

    @Test
    public void insert(a){
        Tesla tesla = new Tesla();
        tesla.setName("Roadster 2022");
        tesla.setPrice(1200000.00);
        tesla.setVehicleType("Sports car");
        tesla.setFactory("The Flamont Gigafactory, California.");

        boolean save = teslaService.save(tesla);
        System.out.println("Whether the file is saved successfully:" + save);
        System.out.println("The ID of the saved record is:" + tesla.getId());
    }

    @Test
    public void getById(a){
        Tesla tesla = teslaService.getById(1166057517);
        System.out.println("The records obtained by ID are:" + tesla);
    }

    @Test
    public void update(a){
        Tesla tesla = new Tesla();
        tesla.setId(1166057517);
        tesla.setName("Cyberpickup 2022");

        boolean update = teslaService.update(tesla, null);
        System.out.println("Update successful:" + update);
    }

    @Test
    public void remove(a){
        boolean remove = teslaService.removeById(1166057517);
        System.out.println("Successfully removed:"+ remove); }}Copy the code

Execute the save method

Execute the getById method

Execute update method

Execute the remove method