MyBatisPlus rapid development

Target

  • Learn about MyBatisPlus' code generator

5. Rapid development


5.1 Principle Analysis of Code Generator

In a sentence:

We can fill in the blank content to make sentences, for example:

In e.g.:

Observing the code we wrote before, we will find that there will be a lot of repetition, such as:

Then we thought, if I want to develop a Book module, do I just need to replace all the content in the red part Book, such as:

So we will find that for the development of any module, for this code, it is basically an adjustment to the red part, so we call the thing that removes the red contenttemplate, the red part is calledparameterIn the future, you only need to pass in different parameters to create dao codes of different modules according to the template.

Except that Dao can extract modules, in fact, all our common classes can be extracted, as long as they have common parts. Let's look at the template of the model class:

  • ① It can be filled according to the table name of the database table
  • ② The ID generation strategy can be generated according to the user's configuration
  • ③ to ⑨ can be filled according to the database table field name

So as long as we know which table to code-generate, we can fill in these contents.

After the analysis, we will find that in order to complete the automatic code generation, we need the following:

  • Template: Provided by MyBatisPlus, you can provide it yourself, but it is troublesome and not recommended
  • Database-related configuration: read the database to obtain table and field information
  • Developer custom configuration: manual configuration, such as ID generation strategy

5.2 Code generator implementation


Step 1: Create a Maven project


Step 2: Import the corresponding jar package

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
    </parent>
    <groupId>com.itheima</groupId>
    <artifactId>mybatisplus_04_generator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--spring webmvc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mybatisplus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

        <!--代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!--velocity模板引擎-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


Step 3: Write the bootstrap class

@SpringBootApplication
public class Mybatisplus04GeneratorApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(Mybatisplus04GeneratorApplication.class, args);
    }

}

Step 4: Create Code Generation Classes

public class CodeGenerator {
    
    
    public static void main(String[] args) {
    
    
        //1.获取代码生成器的对象
        AutoGenerator autoGenerator = new AutoGenerator();

        //设置数据库相关配置
        DataSourceConfig dataSource = new DataSourceConfig();
        dataSource.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        autoGenerator.setDataSource(dataSource);

        //设置全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir")+"/mybatisplus_04_generator/src/main/java");    //设置代码生成位置
        globalConfig.setOpen(false);    //设置生成完毕后是否打开生成代码所在的目录
        globalConfig.setAuthor("黑马程序员");    //设置作者
        globalConfig.setFileOverride(true);     //设置是否覆盖原始生成的文件
        globalConfig.setMapperName("%sDao");    //设置数据层接口名,%s为占位符,指代模块名称
        globalConfig.setIdType(IdType.ASSIGN_ID);   //设置Id生成策略
        autoGenerator.setGlobalConfig(globalConfig);

        //设置包名相关配置
        PackageConfig packageInfo = new PackageConfig();
        packageInfo.setParent("com.aaa");   //设置生成的包名,与代码所在位置不冲突,二者叠加组成完整路径
        packageInfo.setEntity("domain");    //设置实体类包名
        packageInfo.setMapper("dao");   //设置数据层包名
        autoGenerator.setPackageInfo(packageInfo);

        //策略设置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setInclude("tbl_user");  //设置当前参与生成的表名,参数为可变参数
        strategyConfig.setTablePrefix("tbl_");  //设置数据库表的前缀名称,模块名 = 数据库表名 - 前缀名  例如: User = tbl_user - tbl_
        strategyConfig.setRestControllerStyle(true);    //设置是否启用Rest风格
        strategyConfig.setVersionFieldName("version");  //设置乐观锁字段名
        strategyConfig.setLogicDeleteFieldName("deleted");  //设置逻辑删除字段名
        strategyConfig.setEntityLombokModel(true);  //设置是否启用lombok
        autoGenerator.setStrategy(strategyConfig);
        //2.执行生成操作
        autoGenerator.execute();
    }
}

For the code content in the code generator, we can directly obtain the code from the official document for modification,

https://mp.baomidou.com/guide/generator.html


Step 5: Run the program

After running successfully, a lot of code will be generated in the current project, the code contains controller, service, mapperandentity

At this point, the code generator has completed its work, and we can quickly create corresponding classes based on the database tables, simplifying our code development.


5.3 CRUD of Service in MP

Review our previous business layer code writing, write interfaces and corresponding implementation classes:

public interface UserService{
    
    
	
}

@Service
public class UserServiceImpl implements UserService{
    
    

}

After the interface and implementation class are available, methods need to be declared in the interface and implementation class

public interface UserService{
    
    
	public List<User> findAll();
}

@Service
public class UserServiceImpl implements UserService{
    
    
    @Autowired
    private UserDao userDao;
    
	public List<User> findAll(){
    
    
        return userDao.selectList(null);
    }
}

After seeing the above code, MP said that these methods are relatively fixed and general, so I will help you extract them, so MP provides a Service interface and implementation class, which are: and, the latter is a specific implementation of IServicethe ServiceImplformer accomplish.

In the future, the Service we wrote ourselves can be modified as follows:

public interface UserService extends IService<User>{
    
    
	
}

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService{
    
    

}

The advantage after the modification is that MP has helped us realize some basic additions, deletions, changes, and queries of the business layer, which can be used directly.

Write a test class for testing:

@SpringBootTest
class Mybatisplus04GeneratorApplicationTests {
    
    

    private IUserService userService;

    @Test
    void testFindAll() {
    
    
        List<User> list = userService.list();
        System.out.println(list);
    }

}

Note: The MyBatis environment is not configured in the mybatisplus_04_generator project. If you want to run it, you need to extract and improve the content in the configuration file before running it.

Thinking: What methods can be used in the Service layer encapsulated by MP?

View the official documentation: https://mp.baomidou.com/guide/crud-interface.html, you can refer to the official documentation to learn and use these provided methods. The names of the methods may change a bit, but the parameters and return values ​​corresponding to the methods are basically similar.


Study Notes from Dark Horse Programmer

By – Suki 2023/4/7

Guess you like

Origin blog.csdn.net/Eumenides_Suki/article/details/130009781