Mybatis-Puls(MP)

1.Mp简介

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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的快速CRUD

首先安装我们的mybatisx插件;安装之后重启我们的IDEA;
基于SpringBoot创建一个MP的demo如下:
1.1倒入我们需要的依赖

       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>durid-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

创建一个数据库和一个表

CREATE DATABASE `mybatisplus`;

USE `mybatisplus`;

DROP TABLE IF EXISTS `tbl_employee`;

CREATE TABLE `tbl_employee` (
  `id` BIGINT(20) NOT NULL,
  `last_name` VARCHAR(255) DEFAULT NULL,
  `email` VARCHAR(255) DEFAULT NULL,
  `gender` CHAR(1) DEFAULT NULL,
  `age` INT(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=8 DEFAULT CHARSET=gbk;

INSERT  INTO `tbl_employee`(`id`,`last_name`,`email`,`gender`,`age`) VALUES (1,'jack','jack@qq.com','1',35),(2,'tom','tom@qq.com','1',30),(3,'jerry','jerry@qq.com','1',40);

其次书写我们的配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    url: jdbc:mysql:///mybatisplus?serverTimezone=UTC
    password: *******
    #初始化时运行sql脚本
    schema:classpath:sql/schema.sql
    #第一次初始化之后将always变为never
    initialization-mode:always

可以在配置文件中使用脚本来初始化我们的Sql
根据我们的表新建一个实体类
这里使用注解是因为我们表的名字和类名不一样。而我们的BaseMapper是默认使用实体类类名的,也可以将数据库中的名字改为这里的实体类名字!

@Data
@TableName("tbl_employee")
public class Employee {
    private Long id;
    private String lastName;
    private String email;
    private Integer age;

}

新建一个Mapper接口,继承BaseMapper接口,这样就会有基本的增删改查;通过查看BaseMapper,里面的泛型就是我们的实体类,可以发现里面包含如下的方法:
在这里插入图片描述

public interface EmployeeMapper extends BaseMapper<Employee> {

}

在我们的主启动类上添加一个Mapper

@SpringBootApplication
@MapperScan("com.xinan.Mapper")
public class MybatisplusApplication {

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


}

这样我们就可以测试了:

@SpringBootTest
@MapperScan("com.xinan.Mapper")
class MybatisplusApplicationTests {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Test
    void contextLoads() {
         //查询全表
//        List<Employee> employees = employeeMapper.selectList(null);
//        employees.forEach(System.out::println);

        //根据id查询
        System.out.println(employeeMapper.selectById(1));
    }

}

在这里插入图片描述
我们可以通过日志去查看我们的信息:
在配置文件中添加日志信息,因为SpringBoot集成了log



logging:
  level:
    root: info
    com.xinan: debug

再一次运行之后,可以看到日志如下,生成了下面的sql语句;
在这里插入图片描述
同理,我们也可以测试它的删除、更新、增加;

3.MP-通用Service-CRUD

首现在Service层创建一个接口,集成我们的IService,

public interface EmployeeService extends IService<Employee> {
}

其次为我们的Service创建一个实现类,先继承基类ServiceImpl,再去实现我们的接口;

说明:

  • 通用 Service CRUD 封装IService (opens new window)接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
  • 泛型 T 为任意实体对象
  • 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类
  • 对象 Wrapper 为 条件构造器
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

}

此时使用测试类去查询;


@SpringBootTest
class MybatisplusApplicationTests {
    @Autowired
    EmployeeServiceImpl employeeService;

    @Test
    public void query(){
        //根据id查询
        Employee byId = employeeService.getById(1);
        System.out.println(byId);
    }

}

在这里插入图片描述
这里同样的还可以调用IService里所包含的方法,包括save(新增),remove(删除)等方法;

4.分页查询

参考MP的官方文档我们可以发现,分页是需要分页插件的;
MP官网

在这里插入图片描述
首先是没有分页插件是写一个测试类,代码如下:

   @Test
    void page(){
       //表示当前第几页,每页数量多少!
       IPage<Employee> iPage = new Page<Employee>(1,2);
       IPage<Employee> page = employeeService.page(iPage);
       //返回这一页的记录!
       List<Employee> records = page.getRecords();
       //输出这也记录
       System.out.println(records);
       //输出有多少页!
       System.out.println(page.getPages());
   }

在这里插入图片描述
可以看到查询日志里面没有使用limit分页;因此必须配置分页插件;其他配置方式可以查看官网!

@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {

    // 旧版
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
    
    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }
    
}

将最新版的配置文件直接写在我们的主配置类中

@SpringBootApplication
@MapperScan("com.xinan.Mapper")
public class MybatisplusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisplusApplication.class, args);
    }
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //H2数据库需要改成自己使用的数据库
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}

此时加了插件之后,通过查询日志知道里面包含LImit
在这里插入图片描述
输出结果:表示第一页有两条数据,总共有2页!
在这里插入图片描述

5.条件构造器–Wrapper

UpdateWrapper专门用于修改数据!
在这里插入图片描述
首先写一个简单的测试:

@Test
    void contextLoad(){
       QueryWrapper<Employee> objectQueryWrapper = new QueryWrapper<>();
       //可以使用流式编程,条件构造器选择的是lastname和age且lastname为jack;这是硬编码,不利于开发;
       //objectQueryWrapper
//               .select("last_name","age")
//                .eq("last_name","jack");
    

       //用lambda书写
       objectQueryWrapper.lambda()
               .select(Employee::getLast_name,Employee::getAge)
               .eq(Employee::getLast_name,"jack");
       System.out.println(employeeService.list(objectQueryWrapper));
   }

通过日志可以看到
在这里插入图片描述
在这里插入图片描述
这样一来我门还可以通过类似between、allEq等方法,就不用自己去写SQL了,大大降低了开发人员的操作!

6 MP逻辑删除与物理删除

物理删除:在删除的时候直接将数据从数据库中删除;
逻辑删除:从逻辑层面控制删除,通常会在表里添加一个逻辑删除的字段,比如enabled、is_delete,数据默认有效(值为1),当用户删除时将数据修改UPDATE=0,在查询的时候只查where enabled= 1。

首选在对应的实体类中加入逻辑删除标识字段,并对该字段添加@TableLogic注解,其次在数据库中添加一个标识字段,值默认为1;

@Data
@TableName("tbl_employee")
public class Employee {
    @TableLogic
    private Integer delete;
    private Long id;
    private String last_name;
    private String email;
    private int gender;
    private Integer age;
    
}

在这里插入图片描述
此时写一个测试,删除一条数据

  @Test
    void logicDelete(){

        employeeService.removeById(1);
   }

在这里插入图片描述
在这里插入图片描述
只是从逻辑上删除了,但是数据库中存在。此时再用查询去查找的话查不出来这条数据!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值