0411. SpringBoot 整合 Mybatis-Plus【笔记】

1.Mybatis-plus概述

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

2.如何使用MP

1) 初始化一个Spring Boot工程

2) 引入spring-boot-starterspring-boot-starter-testmybatis-plus-boot-starter以及数据库依赖:

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

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

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>最新版本</version>
    </dependency>

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

3)配置

在配置文件中加入数据库的相关配置:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/homework?serverTimezone=Asia/Shanghai

在 SpringBoot 启动类中添加 @MapperScan 注解,扫描Mapper文件:

 4)创建实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {

    @ApiModelProperty("学生编号")
    @TableId(type = IdType.AUTO)
    private Integer stuno;

    @ApiModelProperty("学生姓名")
    private String stuname;

    @ApiModelProperty("学生性别")
    private String gender;

//    @JsonFormat(pattern = "yyyy-MM-dd" , timezone = "GMT%2B8")
    @ApiModelProperty("学生年龄")
    private Date stuage;

    @ApiModelProperty("班级编号")
    private Integer classno;
}

5) 创建Mapper包下的 StudentMapper接口:

public interface StudentMapper extends BaseMapper<Student> {
}

6) 开始使用

添加测试类,进行功能测试:

@SpringBootTest
class Springboot0412ApplicationTests{

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<Student> studentList = studentMapper.selectList(null);
        Assert.assertEquals(5, studentList.size());
        studentList.forEach(System.out::println);
    }

}

* StudentMapper 中的 selectList() 方法的参数为 MP 内置的条件封装器 Wrapper,所以不填写就是无任何条件。

** 从以上步骤中,可以看到集成MyBatis-Plus非常的简单,只需要引入 starter 工程,并配置 mapper 扫描路径即可。

*** 但是MP内置的条件封装Wrapper仅能对单表操作。

3.使用MP完成CRUD

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyx.domain.Student;
import com.cyx.mapper.StudentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
class CyxspringbootmybatisPlusApplicationTests {

    @Autowired
    private StudentMapper studentMapper;

    // 根据ID查询
    @Test
    public void findById() {
        Student student = this.studentMapper.selectById(2201);
        System.out.println(student);
    }

    //添加
    @Test
    public void testInsert(){
        Student student = new Student();
        student.setStuname("bb");
        student.setGender("3-1");
        student.setStuage(9);
        student.setClassno(4);
        int insert = studentMapper.insert(student);
        System.out.println(insert);
    }

    //更新
    @Test
    public void testUpdate(){
        Student student = new Student();
        student.setStuno(2218);
        student.setStuname("abc");
        student.setGender("M");
        student.setStuage(8);
        student.setClassno(2);
        int update = studentMapper.updateById(student);
        System.out.println(update);
    }

    //删除
    @Test
    public void testDeleteById(){
        List<Integer> ids = new ArrayList<>();
        ids.add(2218);
        int delete = studentMapper.deleteBatchIds(ids);
        System.out.println(delete);
    }
}

4..使用MP完成条件查询

  //分页
    @Test
    public void testPage(){
        Page<Student> page = new Page<Student>(1,3);
        Page<Student> studentPage = studentMapper.selectPage(page, null);
        System.out.println("当前页的记录"+ studentPage.getRecords());
        System.out.println("获得当前总页数"+ studentPage.getPages());
        System.out.println("获得总条数"+ studentPage.getTotal());
    }

5.联表使用MP完成分页

StudentMapper:

<mapper namespace="com.cyx.mapper.StudentMapper">

    <resultMap id="findByPageResultMap" type="com.cyx.domain.Student" autoMapping="true">
        <id column="stuno" property="stuno"/>

        <association property="tblclass" javaType="com.cyx.domain.Tblclass" autoMapping="true">
            <id property="classno" column="classno"/>
        </association>
    </resultMap>

    <select id="findByPage" resultMap="findByPageResultMap">
        select * from student s join tblclass c on s.classno = c.classno
        <if test="ew!=null">
            <where>
                and ${ew.sqlSegment}
            </where>
        </if>
    </select>
</mapper>
public interface StudentMapper extends BaseMapper<Student> {
    IPage<Student> findByPage(IPage<Student> iPage, @Param("ew") Wrapper<Student> wrapper);
}

分页工具类(MP提供的插件):

@Configuration
public class MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}

测试类:

    //联表
    @Test
    public void testPage2(){
        Page<Student> page=new Page<>(1,5);
//        QueryWrapper<Student> wrapper=new QueryWrapper<>();
//        wrapper.gt("stuage",3);
        studentMapper.findByPage(page,null);
        System.out.println("当前页的记录"+page.getRecords());//获取当前页的记录
        System.out.println("获取总页数"+page.getPages());//获取当前页的记录
        System.out.println("获取总条数"+page.getTotal());//获取当前页的记录
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值