MyBatis-Plus基础知识、CRUD、主键生成策略、自动填充、乐观锁、分页查询、逻辑删除、性能分析插件、条件构造器、代码生成器、过滤敏感字段、联表分页查询

1.简介

是什么?MyBatis-Plus本来就是简化JDBC操作的!
官网:https://mp.baomidou.com/ MyBatis Plus,简化
在这里插入图片描述

2.特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

3.快速入门

地址:
使用第三方组件:
1.导入对应的依赖
2.研究依赖如何配置
3.代码如何编写
4.提升扩展技术能力

步骤

1.创建数据库‘mybatis_plus’
2.创建user表并增加数据

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id BIGINT(20) NOT NULL COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);
--真实开发中,会存在version(乐观锁)、deleted(逻辑删除)、gmt_create(创建时间)、gmt_modified(修改时间)

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

3.编写项目,使用springboot初始化项目!
4.导入依赖

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

    <!--mybatis-plus-->
    <!--mybatis-plus 是自己开发的,并非官方!-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.0.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--数据库驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>

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

</dependencies>

说明:我们使用mybatis-plus可以节省我们大量的代码,尽量不要同时带入mybatis跟mybatis-plus,可能会产生冲突,一般导入mybatis-plus就够了

5.在application.properties里连接数据库! 这一步和mybatis相同
url字段中 设置时区:serverTime=GMT%2b8 (%2b 就是+的意思,这里是指加8个小时,以北京东八区为准)

# mysql 5 驱动不同,com.mysql.jdbc.Driver,不需要增加时区设置
spring.datasource.username=root
spring.datasource.password=83821979Zs
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# mysql 8 驱动不同,com.mysql.cj.jdbc.Driver,需要增加时区设置
spring.datasource.username=root
spring.datasource.password=83821979Zs
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2b8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

6.pojo-dao(连接mybatis,配置mapper.xml文件)-service-controller

使用了mybatis-plus之后

  • pojo

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
  • mapper接口


// 在对应的Mapper上面实现基本的接口BaseMapper
@Repository  // 代码持久层
@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 所有的CRUD操作都已经编写完成了
    // 你不需要像以前那样配置一大堆文件了
}

在这里插入图片描述

  • 主启动类
    注意:我们需要去主启动类上去扫描我们的mapper包下的所有接口 @MapperScan(com.shuang.mapper)
// 扫描mapper文件夹
@MapperScan("com.shuang.mapper")
@SpringBootApplication
public class MybatisPlusApplication {

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

}
  • 测试类
@SpringBootTest
class MybatisPlusApplicationTests {

    // 继承了BaseMapper,所有的方法都来自自己的父类,我们也可以编写自己的扩展方法
    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        // 查询全部用户
        // selectList(参数) 这里的参数是一个Wrapper,条件构造器,这里我们先不用,写个null占着
        List<User> users = userMapper.selectList(null);
        /*for (User user : users) {
            System.out.println(user);
        }*/

        // 语法糖
        users.forEach(System.out::println);
    }
}

在这里插入图片描述
在这里插入图片描述

思考问题
1.Sql谁帮我们写的?Mybatis-Plus
2.方法哪里来的? Mybatis-Plus都帮我们写好了

4.配置日志

我们所有的Sql现在是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志!

配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

这里我们默认使用默认的控制台输出,使用log4j和slf4j需要导入对应的依赖

在这里插入图片描述
在这里插入图片描述
配置完毕日志之后,后面的学习就需要注意这个自动生成的SQL,我们也就会喜欢MyBatis-Plus!

5.CRUD

插入操作

// 测试插入
@Test
public void testInsert(){
    User user = new User();
    user.setName("小爽帅到拖网速");
    user.setAge(20);
    user.setEmail("1372713212@qq.com");
    int result = userMapper.insert(user);  // 帮我们自动生成id
    System.out.println(result); // 受影响的行数
    System.out.println(user); // 发现,id自动回填
}

在这里插入图片描述

数据库插入id的默认值为:全局唯一ID

主键生成策略

@TableId(type=IdType.ID_WORKER)
默认id_worker 全局唯一

分布式系统唯一ID生成方案:https://www.cnblogs.com/haoxinyue/p/5208136.html

雪花算法:
snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯一!

主键自增
@TableId(type=IdType.AUTO)

我们需要配置主键自增:

1、实体类字段上增加 @TableId(type = IdType.AUTO)

2、数据库字段一定要是设置自增的!
在这里插入图片描述

其余的源码解释

public enum IdType {
    AUTO(0),  // 数据库id自增
    NONE(1),  // 未设置主键
    INPUT(2), // 手动输入
    ID_WORKER(3), // 默认的全局id
    UUID(4),  // 全局唯一id
    ID_WORKER_STR(5); // ID_WORKER 字符串表示法
}

改为手动输入之后,就需要自己配置id

public class User {

    // 对应数据库的主键(uuid、自增id、雪花算法、redis、zookeeper)
    @TableId(type = IdType.INPUT)  // 默认方案
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

在这里插入图片描述

更新操作

更新操作

// 测试更新
@Test
public void testUpdate(){
    User user = new User();
    user.setId(10L);
    user.setName("小爽10L");
    user.setAge(100);
    // 注意: updateById 但是参数是一个对象
    int i = userMapper.updateById(user);//更改
    User user1 = userMapper.selectById(10L);//根据Id查询
    System.out.println(user1);
    System.out.println("受影响的行数"+i);
}

在这里插入图片描述
所有的sql都是自动帮你配置的!

自动填充

创建时间、修改时间!这些个操作一般都是自动化完成的,我们不希望手动更新!

阿里巴巴开发手册:所有的数据库表:gmt_create(创建时间) 、gmt_modify(修改时间)几乎所有的表都要配置上,而且需要自动化!

方式一:数据库级别的修改 (工作中是不允许你修改数据库)

1、在表中新增字段create_time、update_time
在这里插入图片描述
2、再次测试插入方法,我们需要先把实体类同步!
在这里插入图片描述
在这里插入图片描述

方式二:代码级别

1.删除数据库的默认值,更新操作
在这里插入图片描述
2.实体类字段属性上需要增加注解
在这里插入图片描述
3.编写处理器来处理这个注解即可!
由于这个处理器在Springboot下面, mybatis会自动处理我们写的所有的处理器
当我们执行插入操作的时候,自动帮我们通过反射去读取哪边有对应注解的字段,从而把处理器代码插入成功,会自动帮我把createTime,updateTime插入值

package com.shuang.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;



@Slf4j
@Component  // 一定不要忘记把处理器加到IOC容器中!
public class MyMetaObjectHandler implements MetaObjectHandler {

    // 插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill.....");
        // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
        this.setFieldValByName("create_time",new Date(),metaObject);
        this.setFieldValByName("update_time",new Date(),metaObject);
    }
    // 更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("update_time",new Date(),metaObject);
    }
}

4.测试插入

5.测试更新、观察时间即可

乐观锁

在面试过程中,我们经常会被问道乐观锁,悲观锁,其实原理非常简单

在面试过程中,我们经常会被问道乐观锁,悲观锁,其实原理非常简单

顾名思义十分乐观,它总是认为不会出现问题,无论干什么都不会上锁!如果出现问题就再次更新测试

这里引出 旧version 新version

乐观锁:当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败‘
乐观锁:1、先查询,获得版本号 version = 1
-- A
update user set name = "xiaoshaung",version = version + 1
where id = 2 and version = 1

-- B 线程抢先完成,这个时候 version = 2 ,会导致 A 修改失败!
update user set name = "小爽",version = version + 1
where id = 2 and version = 1

测试Mybatis-Plus的乐观锁实现

1、给数据库中增加version字段
在这里插入图片描述
2、实体类加对应的字段

//乐观锁version注解 
@Version  
private Integer version;

3、注册组件

package com.shuang.config;
// 这个扫描本来是在我们MybatisPlusApplication 主启动类中,现在我们把它放在配置类中
// 扫描mapper文件夹
@MapperScan("com.shuang.mapper")
@EnableTransactionManagement  // 自动开启事务管理
@Configuration // 配置类

public class MybatisPlusConfig {

    // 注册乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }
}

4、测试一下乐观锁的使用

// 测试乐观锁单线程成功
@Test
public void testOptimisticLock(){
    // 1、查询用户信息
    User user = userMapper.selectById(1);
    // 2、修改用户信息
    user.setName("xiaoshaung");
    user.setEmail("123123132@qq.com");
    // 3、执行更新操作
    userMapper.updateById(user);
}

在这里插入图片描述

// 测试乐观锁多线程失败  多线程
 /*
 线程1 虽然执行了赋值语句,但是还没进行更新操作,线程2就插队了抢先更新了,
 由于并发下,可能导致线程1执行不成功
 如果没有乐观锁就会覆盖线程2的值
 */
@Test
public void testOptimisticLock2(){
    // 线程1
    User user = userMapper.selectById(1);
    user.setName("xiaoshaung111");
    user.setEmail("123123132@qq.com");

    // 模拟另外一个线程执行了插队操作
    // 线程2
    User user2 = userMapper.selectById(1);
    user2.setName("xiaoshaung222");
    user2.setEmail("123123132@qq.com");
    userMapper.updateById(user2);

    // 自旋锁来多次尝试提交
    userMapper.updateById(user);
}

完成修改的是线程2

悲观锁

顾名思义十分悲观,它总是认为会出现问题,无论干什么都上锁!再去操作

我们这里主要讲究乐观锁机制

查询操作

// 测试查询
    @Test
    public void testSelectById(){
        // 查询一个
        User user = userMapper.selectById(1);
        // 查询批量查询
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
        users.forEach(System.out::println);
        System.out.println(user);
    }

在这里插入图片描述

// 条件查询 map
@Test
public void testSelectByBatchIds(){
    HashMap<String, Object> map = new HashMap<>();
    // 自定义要查询的条件
    map.put("name","宇智波佐助");
    List<User> users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}

在这里插入图片描述

// 条件查询 map
@Test
public void testSelectByBatchIds(){
    HashMap<String, Object> map = new HashMap<>();
    // 自定义要查询的条件
    map.put("name","Tom");
    map.put("age","28");
    List<User> users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}

在这里插入图片描述

分页查询

分页在网站使用的十分之多!
1.原始的limit 进行分页
2.pageHepler 第三方插件
3.Mybatis-Plus其实也内置了分页插件!

如何使用分页插件

1、拦截器组件即可

package com.kuang.config;
public class MybatisPlusConfig {
    // 分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {

        return new PaginationInterceptor();
    }
}

2、直接使用Page对象即可!

// 测试分页查询
@Test
public void testPage(){
    // 参数1 当前页 ;参数2 页面大小
    Page<User> page = new Page<>(1,5);
    userMapper.selectPage(page,null);

    page.getRecords().forEach(System.out::println);//输出分页后的结果
    System.out.println("getCurrent()"+page.getCurrent());//当前第几页
    System.out.println("page.getSize()"+page.getSize());//输出一页数据的条数
    System.out.println("page.getTotal()"+page.getTotal());//输出一共多少条数据
}

在这里插入图片描述
其实每次做分页查询之前都会进行总数查询
在这里插入图片描述

删除操作

1、根据id删除记录

// 测试删除
@Test
public void testDeleteId(){
    userMapper.deleteById(1367357737224667139L );
}

2、批量删除

// 批量删除
@Test
public void testDeleteBatchId(){
    userMapper.deleteBatchIds(Arrays.asList(1367357737224667142L,1367357737224667143L));
}

在这里插入图片描述
3、通过map定制删除

//通过map删除
@Test
public void testDeleteMap(){
    HashMap<String, Object> map = new HashMap<>();
    map.put("id","1367357737224667144");
    userMapper.deleteByMap(map);
}

逻辑删除

物理删除:从数据库中直接移除
逻辑删除:再数据库中没有被移除,而是通过一个变量来让它失效! deleted = 0 => deleted = 1
说明:
只对自动注入的sql起效:

  • 插入: 不作限制
  • 查找: 追加where条件过滤掉已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段
  • 更新: 追加where条件防止更新到已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段
  • 删除: 转变为 更新

例如:

  • 删除: update user set deleted=1 where id = 1 and deleted=0
  • 查找: select id,name,deleted from user where deleted=0

字段类型支持说明:

  • 支持所有数据类型(推荐使用 Integer,Boolean,LocalDateTime)
  • 如果数据库字段使用datetime,逻辑未删除值和已删除值支持配置为字符串null,另一个值支持配置为函数来获取值如now()

附录:

  • 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除。
  • 如果你需要频繁查出来看就不应使用逻辑删除,而是以一个状态去表示。

管理员可以查看被删除的记录! 防止数据的丢失,类似于回收站!
测试一下:

1.在数据表中增加一个deleted字段
在这里插入图片描述
2.实体类中增加字段

// 逻辑删除注解
@TableLogic
private Integer deleted;

3.配置

public class MybatisPlusConfig {
    // 逻辑删除组件
    @Bean
    public ISqlInjector iSqlInjector(){
        return new LogicSqlInjector();
    }
}
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value= 1
mybatis-plus.global-config.db-config.logic-not-delete-value= 0

4.测试一下删除
在这里插入图片描述
让我们来查看一下数据库
在这里插入图片描述
发现记录还在数据库中,但是deleted已经变化了

让我们来重新查询刚才被删除的记录

在这里插入图片描述

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5377414a] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1315188449 wrapping com.mysql.cj.jdbc.ConnectionImpl@29ebbdf4] will not be managed by Spring
==>  Preparing: SELECT id,name,age,email,version,deleted,create_time AS create_time,update_time AS update_time FROM user WHERE id=? AND deleted=0  // 这里查询的是默认未被删除的 0
==> Parameters: 10(Integer)
<==      Total: 0

总结

以上的所有CRUD操作以及其拓展操作,我们都必须精通掌握,会大大提高我们的工作和写项目的效率

6.性能分析插件

我们在平时的开发中,会遇到一些慢sql。
作用:性能分析拦截器,用于输出每条SQL语句及其执行时间
MybatisPlus也提供了性能分析插件,如果超过这个时间就停止运行!
1.导入插件

// SQL 执行效率插件
@Bean
@Profile({"dev","test"}) // 设置 dev  test 环境开启, 保证我们的效率
public PerformanceInterceptor performanceInterceptor(){
    PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
    // 在工作中,不允许用户等待
    performanceInterceptor.setMaxTime(100); // 设置sql执行的最大时间,如果超过了则不执行
    performanceInterceptor.setFormat(true); // 开启sql格式化
    return performanceInterceptor;
}

2.配置Springboot测试环境为dev 或test

# 设置开发环境
spring.profiles.active=dev

3.测试使用

@Test
void contextLoads() {
    // 查询全部用户
    // selectList(参数) 这里的参数是一个Wrapper,条件构造器,这里我们先不用,写个null占着
    List<User> users = userMapper.selectList(null);
    /*for (User user : users) {
        System.out.println(user);
    }*/
    // 语法糖
    users.forEach(System.out::println);
}

只要超过了测试时间就会报错
在这里插入图片描述
这里使用到了SQL格式化工具
在这里插入图片描述
使用我们的性能分析插件就会提高的我们的效率

7.条件构造器

十分重要:Wrapper
我们写一些复杂的sql就可以使用它来替代!
1、非空 大于

@Test
void contextLoads(){
    // 查询 name 不为空的用户,并且邮箱不为空的用户,年龄大于等于20
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
            .isNotNull("name")
            .isNotNull("email")
            .ge("age",20);
    userMapper.selectList(wrapper).forEach(System.out::println);
}

在这里插入图片描述
2、查询一个名字

@Test
void getOneName(){
    // 查询名字 小爽帅到拖网速
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("name","小爽帅到拖网速");  // 查询一个数据,查询多个结果用List或者Map
    userMapper.selectOne(wrapper);
}

在这里插入图片描述
3.使用between

@Test
void betweenTest(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.between("age",25 ,100);//25-100岁之间
    Integer count = userMapper.selectCount(wrapper);// 查询结果数
    System.out.println(count);
}

在这里插入图片描述
4、like模糊查询

// 模糊查询
@Test
void likeTest(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    // 左和右
    wrapper.notLike("name","帅")
           .likeRight("name","小");
    List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
    maps.forEach(System.out::println);
}

在这里插入图片描述
注意:这里查询的是 name 中不带“帅”字,且模糊查询为 “小%”,而在我们现在的数据库中有两个是符合查询条件,但是只查询出一个结果,原因是还有一个被我们逻辑删除了,deleted = 1
在这里插入图片描述
5、连接查询(内查询)

// 内查询
@Test
void innerJoinTest(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    // id 在子查询中查找出来的
    wrapper.inSql("id","select id from user where id<3");
    List<Object> users = userMapper.selectObjs(wrapper);
    users.forEach(System.out::println);
}

在这里插入图片描述

6、升序排序

// 通过id进行排序
@Test
void orderById(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //
    wrapper.orderByDesc("id");
    List<Object> objects = userMapper.selectObjs(wrapper);
    objects.forEach(System.out::println);
}

在这里插入图片描述

8.代码生成器

dao、pojo、service、controller 都自己编写完成

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

注意:在全局配置中总有一句代码,怎么写都是爆红,我一开始以为是依赖冲突,一直去换依赖,步步排查才发现原来是有依赖导错了
在这里插入图片描述
在这里插入图片描述

// 代码自动生成器
public class AutoGeneratorTest {
    public static void main(String[] args) {
        // 需要构建一个 代码自动生成器 对象
        AutoGenerator mpg = new AutoGenerator();
        // 配置策略

        // 1、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("小爽帅到拖网速");
        gc.setOpen(false);
        gc.setFileOverride(false);  // 是否覆盖
        gc.setServiceName("%Serive"); // 服务接口,去Service的I前缀
        gc.setIdType(IdType.ID_WORKER); // 主键生成策略
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);

        // 给代码自动生成器注入配置
        mpg.setGlobalConfig(gc);

        // 2、 设置数据源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2b8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("83821979Zs");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 3、包的配置

        PackageConfig pc = new PackageConfig();
        pc.setModuleName("blog");
        pc.setParent("com.shuang");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");

        mpg.setPackageInfo(pc);

        // 4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user"); // 设置要映射的表名,想要生成新的实体类,这里可以写多个对应数据库的表,运行会生成代码下图
        strategy.setNaming(NamingStrategy.underline_to_camel);  // 内置下划线转驼峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);  // 自动Lombok

        strategy.setLogicDeleteFieldName("deleted");  // 逻辑删除字段

        // 自动填充策略
        TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
        TableFill gmtModifid = new TableFill("gmt_modifid", FieldFill.INSERT);

        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate);
        tableFills.add(gmtModifid);
        strategy.setTableFillList(tableFills);

        // 乐观锁
        strategy.setVersionFieldName("version");

        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true); // Localhost:8080/hello_id_2

        mpg.setStrategy(strategy);

        // 执行
        mpg.execute();
    }
}

在这里插入图片描述
在这里插入图片描述

9.过滤敏感字段

有的时候有一些敏感数据不方便发给前端,比如用户的密码信息、一些不需要的字段、不能给前端看的数据字段,这个时候这种字段就需要过滤一下
9.1 创建一个要返回给前端的数据实体

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentVo {
    private Long id;
    private String name;
    private Integer sex;
    private Integer age;
    private Long classId;
    //StudnetVo转Student的方法
    public Student tranferView(Student model){
		this.studentId=model.getStudentId();
		this.name=model.getName();
		this.sex=model.getSex();
		this.age=model.getAge();
		this.classId=model.getClassId();
		或者
		BeanUtils.copyProperties(model,this);
		return this;
}
    // 在这边 我们认为下面的几个字段是不需要给前端的,将其取消掉
    // 代码中不用写,这边只是为了突出不要的是这几个字段
    // private Date createTime;
    // private String createBy;
    // private Date updateTime;
    // private String updateBy;
    // private Integer delFlag;
}

9.2 传统方法

@GetMapping("/list")
public List<StudentVo> queryList() {
    Page<Student> studentPage = new Page<>(1, 5);
    Page<Student> page = service.page(studentPage);
    List<Student> students = page.getRecords();
    List<StudentVo> studentVos = new ArrayList<>();
    // 循环对象集合,对需要保存的字段进行赋值加入集合
    for (Student s : students) {
        StudentVo s2 = new StudentVo();
        s2.setName(s.getName());
        s2.setClassId(s.getClassId());
        s2.setSex(s.getSex());
        // 可以发现,如果字段很多那么这个操作很繁琐,也可以在StudentVo里面写一个转换方法tranferView
        studentVos.add(s2);
    }
    return studentVos;
}

9.3 使用BeanUtils工具
在这里插入图片描述

@GetMapping("/list")
public List<StudentVo> queryList() {
    Page<Student> studentPage = new Page<>(1, 5);
    Page<Student> page = service.page(studentPage);
    List<Student> students = page.getRecords();
    List<StudentVo> studentVos = new ArrayList<>();
    // 循环对象集合,对需要保存的字段进行赋值加入集合
    for (Student s : students) {
        StudentVo s2 = new StudentVo();
        // 简化操作,但是效率比较低
        BeanUtils.copyProperties(s,s2);//也可以将这个方法写入StudentVies中tranferView方法中直接调用
        studentVos.add(s2);
    }
    return studentVos;
}

9.4 使用插件 mapstruct
导入依赖

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>1.4.2.Final</version>
</dependency>
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.4.2.Final</version>
</dependency>

建一个专门用于映射的文件夹mapping

@Mapper
public interface StudentMapping {
   StudentMapping INSTANCE = Mappers.getMapper(StudentMapping.class);
   StudentVo toStudentVo(Student student);
}

使用

@GetMapping("/list")
public List<StudentVo> queryList() {
    Page<Student> studentPage = new Page<>(1, 5);
    Page<Student> page = service.page(studentPage);
    List<Student> students = page.getRecords();
    List<StudentVo> studentVos = new ArrayList<>();
    // 循环对象集合,对需要保存的字段进行赋值加入集合
    for (Student s : students) {
        StudentVo s2 = StudentMapping.INSTANCE.toStudentVo(s);
        studentVos.add(s2);
    }
    return studentVos;
}

也可以直接处理list

@Mapper
public interface StudentMapping {
    StudentMapping INSTANCE = Mappers.getMapper(StudentMapping.class);
    StudentVo toStudentVo(Student student);
    List<StudentVo> toStudentVoList(List<Student> studentList);
}
@GetMapping("/list")
public List<StudentVo> queryList() {
    Page<Student> studentPage = new Page<>(1, 5);
    Page<Student> page = service.page(studentPage);
    List<Student> students = page.getRecords();
    List<StudentVo> studentVos = StudentMapping.INSTANCE.toStudentVoList(students);
    return studentVos;
}

上述三种方法性能最高的是:传统方法,mapstruct,BeanUtils。

10.联表分页查询

分页查询班级和班级下的学生信息

10.1 创建要返回的数据的实体类

@Data
public class ClassStudentVo {
    private Long id;
    private String name;
    private List<Student> studentList;
}

创建ClassMapper

@Repository
public interface ClassMapper extends BaseMapper<ClassStudentVo> {
    //分页查询班级和班级下的学生信息
    //page为分页对象,wrapper为查询条件
    // 由于Mybatis本身没有联表查询的操作,所以我们要自己手写一个方法来实现
    Page<ClassStudentVo> queryClassAndStudent(@Param("page") Page<ClassStudentVo> page,@Param(Constants.WRAPPER) Wrapper<ClassStudentVo> wrapper);
}

接口中创建方法

public interface IClassService extends IService<ClassStudentVo> {
    Page<ClassStudentVo> queryClassAndStudent(Page<ClassStudentVo> page, Wrapper<ClassStudentVo> wrapper);
}

实现类重写方法

@Service
public class ClassService extends ServiceImpl<ClassMapper, ClassStudentVo> implements IClassService {
    @Autowired
    private ClassMapper mapper;

    @Override
    public Page<ClassStudentVo> queryClassAndStudent(Page<ClassStudentVo> page, Wrapper<ClassStudentVo> wrapper) {
        return mapper.queryClassAndStudent(page, wrapper);
    }
}

两种实现方式

  • 集中式

ClassController.java

@GetMapping("/queryClassAndStudent")
public List<ClassStudentVo> queryAll(ClassStudentVo classStudentVo) {
    Page<ClassStudentVo> classPage = new Page<>(1, 5);
    QueryWrapper<ClassStudentVo> wrapper = new QueryWrapper<>();
    wrapper.eq("c.class_id", "1");
    Page<ClassStudentVo> page = service.queryClassAndStudent(classPage, wrapper);
    System.out.println(page.getTotal());
    return page.getRecords();
}

classMapper.xml

<!--  配置关联  -->
<resultMap id="classStudentVoRes" type="com.example.demo.entity.vo.ClassStudentVo">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="studentList" ofType="com.example.java22springboot.entity.Student" autoMapping="true">
            <id property="studentId" column="studentId"/>
            <result property="name" column="studentName"/>
            <result property="age" column="age"/>
        </collection>
</resultMap>
<!--  查询语句  -->
<select id="queryClassAndStudent" resultMap="classStudentVoRes">
    SELECT c.class_id id,
    c.name,
    s.student_id studentId,
    s.name studentName,
    s.sex,
    s.age,
    s.class_id
    FROM class c
    LEFT JOIN student s on c.class_id = s.class_id
    <!-- ${ew.customSqlSegment}这个是固定写法一定要加,不然条件就无效了 -->
    ${ew.customSqlSegment}
</select>
  • 分布式

ClassController.java

@GetMapping("/queryClassAndStudent2")
public List<ClassStudentVo> queryAll2() {
    Page<ClassStudentVo> classPage = new Page<>(1, 5);
    QueryWrapper<ClassStudentVo> wrapper = new QueryWrapper<>();
     wrapper.eq( "class_id", "1");
    Page<ClassStudentVo> page = service.queryClassAndStudent(classPage, wrapper);
    System.out.println(page.getTotal());
    return page.getRecords();
}

classMapper.xml\

<!--  配置关联  -->
<resultMap id="classStudentVoRes2" type="com.example.demo.entity.vo.ClassStudentVo">
        <id property="id" column="id"/>
        <!--            <result property="name" column="name"/>-->
        <collection property="studentList"
                    ofType="com.example.java22springboot.entity.Student"
                    select="getStudentsByClassId"
                    column="{classId=id}"/>
</resultMap>
<!--  班级的查询  -->
<select id="queryClassAndStudent" resultMap="classStudentVoRes2">
        SELECT class_id id,name FROM class
        <!-- ${ew.customSqlSegment}这个是固定写法一定要加,不然条件就无效了 -->
        ${ew.customSqlSegment}
</select>
<!--  内部的子查询  -->
<select id="getStudentsByClassId" resultType="com.example.demo.entity.Student">
        SELECT *
        FROM student
        WHERE class_id = #{classId}
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值