MyBatis Plus for Data Access (3) - MPG Code Generator

"Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-in Event, click to view the details of the event ."

One, MyBatis Plus and MyBatis code generator comparison

  • A large number of custom settings are provided in MPG, and the generated code can fully meet the needs of various types
  • Strategy selection for table name and field naming
    • In MPG, database table names and field names can be named by hump or by glide. The dbColumnUnderline configuration in MyBatis Plus is enabled by default. MPG recommends using camel case naming, so that fields do not need to be mapped and directly correspond to entity classes and entity class attributes, which can avoid mapping performance loss; using underscore naming requires opening hump conversion rules
  • MPG can generate Entity entity class, Mapper interface, Mapper mapping file, Service layer, Controller layer
  • MBG can generate Entity entity classes, Mapper interfaces, and Mapper mapping files

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

2. MyBatis Plus Code Generator MPG

Engineering construction

Use IDEA to create a Maven project mybatis-plus-mpg, the related dependencies used and the Spring and MyBatis Plus global configuration files and database log files can refer to MyBatis Plus of Data Acces (1) - BaseMapper CRUD (Part A) created in mybatis -plus works.

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

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>
复制代码

Since MPG will generate the Controller layer, it is necessary to add the relevant dependencies of Spring Web MVC

<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>
复制代码

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=true";
    private static final String JDBC_USERNAME = "root";
    private static final String JDBC_PASSWORD = "root";
    // 代码生成器
    @Test
    public void generator(){

        FastAutoGenerator.create(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD)
                .globalConfig(builder -> {
                    builder.author("Jingnan") // 设置作者
                            //.enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("src/main/java"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com") // 设置父包名
                            .moduleName("lilith") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "src/main/resources/mappers/")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("t_tesla").addInclude("porsche") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

    }
}
复制代码

The code in the generator method is copied from the official website of MyBatis Plus, and only the database connection information and package name information are modified.

run the generator method

image.pngAccording to the log output from the console, it can be seen that the code generation has been completed

View directory structure

image.png

MPG automatically generates the controller layer, service layer, mapper interface and mapper XML file

If you want to generate the corresponding code for multiple tables at one time, you can directly addInclude("porsche")image.png

For more configuration, please refer to MyBatis Plus Code Generator

3. Test the code generated by MPG

Test TeslaMapper

Create a new TeslaMapperTest to test the TeslaMapper interface

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

    @Resource
    private TeslaMapper teslaMapper;

    @Test
    public void insert(){
        Tesla tesla = new Tesla();
        tesla.setName("Model 3P 2022");
        tesla.setVehicleType("四门轿车");
        tesla.setPrice(270000.00);
        tesla.setFactory("特斯拉上海超级工厂");

        int count = teslaMapper.insert(tesla);
        System.out.println("执行INSERT操作后更新的行数:" + count);
    }

    @Test
    public void selectById(){
        Tesla tesla = teslaMapper.selectById(6);
        System.out.println("执行SELECT查询到的数据:" + tesla);
    }

    @Test
    public void update(){
        Tesla tesla = new Tesla();
        tesla.setId(1166057516);
        tesla.setFactory("特斯拉柏林超级工厂");

        int count = teslaMapper.updateById(tesla);
        System.out.println("执行UPDATE操作后更新的行数:" + count);
    }

    @Test
    public void delete(){
        int count = teslaMapper.deleteById(1166057516);
        System.out.println("执行DELTE操作后更新的行数:" + count);
    }
}
复制代码

Execute the insert methodimage.png

Execute the selectById methodimage.png

Execute the udpdate methodimage.png

Execute the delete methodimage.png

Test ITeslaService

Create a new test class ITeslaServiceTest for ITeslaService

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

    @Resource
    private ITeslaService teslaService;

    @Test
    public void insert(){
        Tesla tesla = new Tesla();
        tesla.setName("Roadster 2022");
        tesla.setPrice(1200000.00);
        tesla.setVehicleType("跑车");
        tesla.setFactory("加州弗拉蒙特超级工厂");

        boolean save = teslaService.save(tesla);
        System.out.println("是否保存成功:" + save);
        System.out.println("保存成功的记录的ID为:" + tesla.getId());
    }

    @Test
    public void getById(){
        Tesla tesla = teslaService.getById(1166057517);
        System.out.println("根据ID获取的记录为:" + tesla);
    }

    @Test
    public void update(){
        Tesla tesla = new Tesla();
        tesla.setId(1166057517);
        tesla.setName("赛博皮卡 2022");

        boolean update = teslaService.update(tesla, null);
        System.out.println("是否更新成功:" + update);
    }

    @Test
    public void remove(){
        boolean remove = teslaService.removeById(1166057517);
        System.out.println("是否移除成功:" + remove);
    }


}
复制代码

Execute the save methodimage.png

Execute the getById methodimage.png

Execute the update methodimage.png

Execute the remove methodimage.png

Guess you like

Origin juejin.im/post/7080093649517674504