springboot + Mybatis-plus

springboot + Mybatis-plus

学习笔记文档

作者--Alianer


简介

一些链接

Mybatis-plus特性

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

配置

依赖配置

pom.xml: 我这里选择的最新版本和连接的mysql数据库。(不建议Mybatis-plus和Mybatis一起使用避免不必要的报错)

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

<!--      mybatis-plus依赖 最新3.4.2-->
      <dependency>
         <groupId>com.baomidou</groupId>
         <artifactId>mybatis-plus-boot-starter</artifactId>
         <version>3.4.2</version>
      </dependency>

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

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

<!--      lombok-->
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>

application

application.yml: 大致和配置Mybatis一致,多一个配置日志

#端口号配置
server:
  port: 8084

#数据库链接(我的数据库没用设置密码所以password是空的)
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/web_01?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password:
    
#配置mybatis-plus日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

类配置

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:(官方做法)

@SpringBootApplication
@MapperScan("com.pg.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(QuickStartApplication.class, args);
    }
}

我是推荐在com.pg下的config层里面创建一个MybatisPlusConfig类在哪里添加@MapperScan 注解

@MapperScan("com.pg.mapper") //扫描mapper文件夹
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
}

项目结构

springboot

这里先贴出实体类和mapper接口的代码,config,和handler后面会再做解释

在这里插入图片描述

mapper接口UserMapper:

@Repository
public interface UserMapper extends BaseMapper<User> {
}

实体类User:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    //主键,AUTO自增,必须在数据库里面也设置自增才行
    @TableId(type = IdType.AUTO)
    private int id;
    private String name;
    private String pwd;

    //插入和更新时候刷新,给字段填充内容
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

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

    @TableLogic     //逻辑删除
    private Integer deleted;
}

数据库

数据库名web_01下的user表:

在这里插入图片描述

扩展&插件

执行 SQL 分析打印

pom.xml配置依赖:

<!--       p6spy依赖    最新3.9.1-->
      <dependency>
         <groupId>p6spy</groupId>
         <artifactId>p6spy</artifactId>
         <version>3.9.1</version>
      </dependency>

在resources下创建spy.properties 配置sql分析的逻辑规则 (官方最新配置信息)

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

自动填充

实体类对应的字段添加@TableField注解(这里给createTime和updateTime字段添加自动填充,数据更新或者插入时候会按照逻辑给对应字段填充信息)

//插入和更新时候刷新,给字段填充内容
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

com.pg.handler下创建一个MyMetaObjectHandler类处理自动填充的逻辑

//使用@Slf4j以后,默认的Slf4j对象就是log,所以使用时候可以直接log.info()、log.error()……,
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//    插入时候的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("insert fill...");
//        setFieldValByName(java.lang.String fieldName, java.lang.Object fieldVal, org.apache.ibatis.reflection.MetaObject metaObject)
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
// 更新时候的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("update fill...");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

乐观锁&分页

乐观锁:顾名思义这个锁是乐观的,就是任何时候都不会上锁直到出现异常。

悲观锁:和乐观锁相反,任何操作时刻都会上锁,直到没用异常

乐观锁具体实现方法:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

实体类:

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

MybatisPlusConfig类: 新版的乐观锁和分页的bean我放一起了

@MapperScan("com.pg.mapper") //扫描mapper文件夹
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    // 注册乐观锁和分页插件(新版:3.4.0)
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 乐观锁插件
        // DbType:数据库类型(根据类型获取应使用的分页方言)
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 分页插件
        return interceptor;
    }
}

在测试类里面乐观锁的简单测试:

简单解释一下,改测试对id为1的用户进行name字段的设置和pwd字段的设置,在模拟线程的情况下,线程1,2同时修改id为1的数据,但是执行更新操作的时候先更新的线程2的更改,导致的版本字段version的改动,这个时候再去执行线程1的更新就会触发乐观锁,导致线程1的更新失败

	@Autowired
	private UserMapper userMapper;    
// 测试乐观锁,失败情况
   @Test
   public void testOptimisticLocker2(){

//    线程1
      userMapper.selectById(1);
      User user = userMapper.selectById(1);
      user.setName("yxz");
      user.setPwd("aaaa");
//    线程2
      userMapper.selectById(1);
      User user2 = userMapper.selectById(1);
      user2.setName("xyz");
      user2.setPwd("bbbb");
//    更新操作
      userMapper.updateById(user2);
      userMapper.updateById(user);
   }

最后的结果只是线程2的更改成功并且保存至数据库

在这里插入图片描述

分页的简单测试

//  分页查询
   @Test
   public void testPage(){
//    定义查询第一页数据,每页4条
      Page<User> page = new Page<>(1,4);
      userMapper.selectPage(page,null);
      page.getRecords().forEach(System.out::println);
   }

输出结果:

在这里插入图片描述

逻辑删除

规范数据库的操作,一般的删除操作都不是真正的删除数据.而是给数据添加一个字段deleted,约定一个规则-已经删除置1,未删除置0,当需要删除该数据时候把对应的字段置1,表示该数据已经被删除.并且对外不可视.

实体类:

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

需要在application.yml里面配置删除的逻辑: 注意global-config是在mybatis-plus下一级的

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

#mybatis-plus下配置逻辑删除,已经删除置1,未删除置0
  global-config:
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0

简单的实现效果:

在这里插入图片描述

如图id为7,14,15的数据已经被逻辑删除,且对外无法查询

在这里插入图片描述

条件查询器Wrapper

方便我们编写一些复杂的查询而不需要像Mybatis一样写在对应的xml里面

以下是我自己写的一些测试类,对wrapper部分功能的使用测试,更多更详细的可以去官方文档查询

@SpringBootTest
public class WrapperTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
//    查询name不为空,并且id大于等于14的用户
        QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.isNotNull("name")
                            .ge("id",14);
        userMapper.selectList(objectQueryWrapper).forEach(System.out::println);
    }

    @Test
    void contextLoads2() {
//    查询一个数据,且id等于16
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",16);
//        输出查询数
        System.out.println(userMapper.selectOne(wrapper));
    }

    @Test
    void contextLoads3() {
//    查询一个数据,且id等于在16到19之间
        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        查询区间
        wrapper.between("id",16,19);
//        得到的是查询结果数
        System.out.println(userMapper.selectCount(wrapper));
    }

//    模糊查询
    @Test
    void contextLoads4() {
//    查询name是c开头的数据
        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        likeLeft等价于: %c   likeRight等价于: c%
        wrapper.likeRight("name","c");
//        遍历输出查询结果
        userMapper.selectList(wrapper).forEach(System.out::println);
    }


    @Test
    void contextLoads5() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        id在子查询中的查询
//        SELECT id,name,pwd,create_time,update_time,version,deleted FROM user WHERE deleted=0 AND (id IN (select id from user where id<15))
        wrapper.inSql("id","select id from user where id<15");
//        遍历输出查询结果
        userMapper.selectList(wrapper).forEach(System.out::println);
    }

    @Test
    void contextLoads6() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        降序排序
        wrapper.orderByDesc("id");
//        遍历输出查询结果
        userMapper.selectList(wrapper).forEach(System.out::println);
    }

}

代码生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。官方也为我们提供了许多方法和模板(点击去官方文档)

配置依赖

pom.xml(必须引进的依赖我在注释里面写了)

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

<!--      mybatis-plus依赖(必须)-->
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>3.4.2</version>
</dependency>
<!--      代码生成器(必须)-->
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-generator</artifactId>
   <version>3.4.1</version>
</dependency>
<!--        MyBatis-Plus 支持 Velocity(可选模板但默认是这个)-->
<dependency>
   <groupId>org.apache.velocity</groupId>
   <artifactId>velocity-engine-core</artifactId>
   <version>2.3</version>
</dependency>
<!--      swagger2(可选,,为了规范文档注释建议添加) -->
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>3.0.0</version>
</dependency>
<!--      p6spy依赖(可选,为了规范sql建议添加)-->
<dependency>
   <groupId>p6spy</groupId>
   <artifactId>p6spy</artifactId>
   <version>3.9.1</version>
</dependency>
<!--      mysql数据库(必须,可以换成你的数据库对应的依赖)-->
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>
<!--      lombok(必须)-->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

注意:

  1. application.yml 和 spy.properties 和之前的配置保持一致
  2. 需要注意config包下的配置还是要自己写,代码生成器只负责快速生成 Entity、Mapper、Mapper XML、Service、Controller 等
代码生成器编写

代码生成器的官方配置(该类可以写在测试类注意头文件需要正确引入,我已经把全部头文件贴出来了)

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;

public class PgCode {
    public static void main(String[] args) {
//         代码生成器
        AutoGenerator mpg = new AutoGenerator();

//         全局配置
        GlobalConfig gc = new GlobalConfig();
//         获取当前项目路径,并且代码生成在src/main/java下
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("Alianer");                //指定作者
        gc.setOpen(false);                      //是否开启资源管理器
        gc.setFileOverride(false);              //是否覆盖
        gc.setServiceName("%sService");         //去掉service的I前缀
        gc.setIdType(IdType.AUTO);              //设置主键的自增策略
        gc.setDateType(DateType.ONLY_DATE);     //设置时间格式
        gc.setSwagger2(true);                   //实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

//         数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/web_01?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
//         dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

//         包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("pkg");        //总体模块名称
        pc.setParent("com.pg");         //生成包的路径在com.pg下
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

//         策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user");        //设置要映射的表
        strategy.setNaming(NamingStrategy.underline_to_camel);      // 数据库字段下划线转驼峰命令策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);        //自动Lombok
        strategy.setRestControllerStyle(true);
//        设置逻辑删除
        strategy.setLogicDeleteFieldName("deleted");
//        自动填充
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time", FieldFill.UPDATE);
        ArrayList<TableFill> tableFill = new ArrayList<>();
        tableFill.add(createTime);
        tableFill.add(updateTime);
        strategy.setTableFillList(tableFill);
//        乐观锁
        strategy.setVersionFieldName("version");
        strategy.setControllerMappingHyphenStyle(true);

        mpg.setStrategy(strategy);
//        执行...
        mpg.execute();
    }
}
最终结果

如图:pkg包下的所有文件都是由代码生成器为我们生成的

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值