Spring Boot 2.6.4 (four) - Data Access (Part D MyBatis Plus)

"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 ."

1. Spring Boot integrates MyBatis Plus

MyBatis Plus is an enhancement framework for MyBatis. It only enhances and does not change on the basis of MyBatis. It is born to simplify development and improve efficiency. MyBatis Plus provides general-purpose Mapper and Service, which can quickly implement CRUD, batch operations, logical delete, and paging operations on a single table without writing any SQL statements.

Use idea to create spring-boot-mybatisplus and import basic dependencies

image.png

MyBatis Plus provides a Spring Boot starter, which can directly import the starter of MyBatis Plus, and then import MyBatis Plus code generator dependencies and template dependencies

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>
复制代码

MyBatis Plus automatic configuration principle The automatic configuration class of MyBatis Plus is MybatisPlusAutoConfiguration under the com.baomidou.mybatisplus.autoconfigure package

image.png

MybatisPlusAutoConfiguration auto configuration class enabled MyBatisPlusProperties configuration classimage.png

The prefix of the MyBatisPlusProperties configuration class is mybatis-plusimage.png

The relevant configuration of mybatis-plus is in the MyBatisPlusProperties configuration class

2. MyBatis Plus implements CRUD

Configure database connection information in application.yml and use Spring Boot's default data source

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: Abc*123456
    url: jdbc:mysql://rm-uf67r962043910k193o.mysql.rds.aliyuncs.com:3306/test
复制代码

Add related configuration of MyBatis Plus

mybatis-plus:
  mapper-locations: classpath:mappers/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
复制代码

Add entity package, add Tesla entity class

@Data
@TableName("t_tesla")
public class Tesla {

    private Integer id;
    private String name;
    private Double price;
    private String vehicleType;
    private String factory;
}
复制代码

Added mapper package, added TeslaMapper interface, added selectTeslaById method

@Mapper
public interface TeslaMapper {

    Tesla selectTeslaById(Integer id);
}
复制代码

在resources目录下增加mpper文件夹,增加TeslaMapper对应的XML文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lilith.mapper.TeslaMapper">
    <sql id="teslaAllColums">
        id,name,price,vehicle_type,factory
    </sql>

    <select id="selectTeslaById" resultType="com.lilith.entity.Tesla">
        SELECT
        <include refid="teslaAllColums"></include>
        FROM t_tesla where id = #{id}
    </select>
</mapper>
复制代码

增加TeslaMapperTest测试类,对selectTeslaById方法进行测试

@SpringBootTest
public class TeslaMapperTest {

    @Resource
    private TeslaMapper teslaMapper;


    @Test
    public void selectTeslaById(){
        Tesla tesla = teslaMapper.selectTeslaById(2);
        System.out.println("查询到的内容为:" + tesla);
    }
}
复制代码

执行该方法

image.png 成功查询到数据,application.yml中MyBatis Plus的配置生效。

继承BaseMapper实现CRUD

TeslaMapper继承MyBatis Plus的BaseMapper接口即可拥有基本CRUD条件查询以及分页方法

@Mapper
public interface TeslaMapper extends BaseMapper<Tesla>{

    Tesla selectTeslaById(Integer id);
}
复制代码

在TeslaMapperTest中测试BaseMapper提供的查询方法

@Test
public void selectOneById(){
    Tesla tesla = teslaMapper.selectById(2);
    System.out.println("MyBatis Plus的SELECT方法查询到的数据:" + tesla);
}
复制代码

执行该方法 image.png

更多MyBatis Plus的CRUD方法以及注解和条件查询可以参考 Data Acces 之 MyBatis Plus(一)- BaseMapper CRUD(Part A)Data Access 之 MyBatis Plus(二)- Wrapper 条件构造器

三、MyBatis Plus 插件使用

在SSM中配置MyBatis Plus插件需要在Spring 配置文件中配置分页插件,然后将分页插件的Bean注入到MybatisSqlSessionFactoryBean中。而在Spring Boot中可以使用配置类的方式,将分页插件的Bean注册到容器中

新建config包,增加MyBatisPlusConfig配置类,将MyBatis Plus用于分页的插件注入到容器中

@Configuration
public class MyBatisPlusConfig {

    public PaginationInnerInterceptor innerInterceptor(){
        PaginationInnerInterceptor interceptor = new PaginationInnerInterceptor();
        interceptor.setDbType(DbType.MYSQL);
        return interceptor;
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.setInterceptors(Arrays.asList(innerInterceptor()));
        return mybatisPlusInterceptor;
    }
}
复制代码

在TeslaMapperTest中测试selectPage方法

@Test
public void selectPage(){

    Page<Tesla> teslaPage = new Page<>(2,4);

    Page<Tesla> page = teslaMapper.selectPage(teslaPage, null);

    System.out.println("--------------------");
    System.out.println("查询当前页面的数据:" + page.getRecords());
    System.out.println("--------------------");
}
复制代码

执行selectPage方法 image.png

根据输出的SQL语句,成功执行了分页查询。

四、MyBatis Plus MPG 代码生成器

使用MyBatis Plus的代码生成器需要导入generator依赖和模板引擎依赖

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

在MybatisplusApplicationTests测试类中添加代码生成器方法的代码

private static final String JDBC_URL = "jdbc:mysql://localhost/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("porsche") // 设置需要生成的表名
                        .addTablePrefix("t_", "c_"); // 设置过滤表前缀
            })
            .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
            .execute();

}
复制代码

Execute this method to generate the controller layer, service layer, mapper layer and mapper XML configuration fileimage.png

Test Controller layer code

Add code in PorscheController

@Controller
@RequestMapping("/lilith/porsche")
public class PorscheController {

    @Autowired
    private IPorscheService porscheService;

    @ResponseBody
    @GetMapping("/list")
    public List<Porsche> list(){
        List<Porsche> list = porscheService.list();
        return list;
    }
}
复制代码

Delete the @Mapper annotation on the TeslaMapper class and add the @MapperScan annotation on the MyBatisplusApplication startup class

@MapperScan(basePackages = "com.lilith.mapper")
复制代码

Start the application and enter http://localhost:8080/lilith/porsche/list in the browser image.png

For the code generator of MyBatis Plus and the test of the Mapper layer and the Service layer, you can also refer to MyBatis Plus of Data Access (3) - MPG Code Generator

Guess you like

Origin juejin.im/post/7080150504071757861