Mybatis-Plus学习笔记

一、MybatisPlus 简介

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

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

二、数据库表与实体类的关系管理 MP ORM

注解位置作用
@TableName标注对应的表名
@TableId属性标注主键字段(value值对应数据库主键字段typ值定义主键策略。Mysql的主键策略为IdType.AUTO)
@TableField属性标记非主键的属性
@Version属性标记用于表示版本的属性,一般为version。
@TableLogic属性标记逻辑删除属性,一般为deleted。value 逻辑未删除值,delval 逻辑删除值
@OrderBy属性内置 SQL 默认指定排序,优先级低于 wrapper 条件查询

三、MP在SpringBoot的使用案例

整合依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
 <dependency>
     <groupId>com.baomidou</groupId>
     <artifactId>mybatis-plus-boot-starter</artifactId>
     <version>3.4.3.2</version>
 </dependency>

配置数据库连接字段

#连接字段
spring.datasource.username=root
spring.datasource.password=123456
# 使用8.0以上的mysql版本需要设置时区
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

应用实例

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
  private Integer id;
  private String name;
  private String pwd;
  private String perm;
}

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

//扫描Mapper
@MapperScan("com.kuang.mapper")
@SpringBootApplication
public class MybatisPlus02Application {
    public static void main(String[] args) {
        SpringApplication.run(MybatisPlus02Application.class, args);
    }
}

//测试
@SpringBootTest
class MybatisPlus02ApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        List<User> userList = userMapper.selectList(null);
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

四、日志功能

MP的日志功能可以查看生成的SQL语句
在SpringBoot项目中添加日志支持

# 日志输出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

在SpringMVC项目中添加日志支持

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 全局参数 -->
    <settings>
        <!--设置日志功能-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
</configuration>

五、SQL条件构造器

MP中给我们提供了方便的表操作方法,这些方法可以帮助我们执行一些简单的SQL命令,这些方法虽然简单却也缺少灵活性。为了对这些方法进行扩展,使之能够更加强大,MP提供了条件构造器解决这个问题。
下例即是使用QueryWrapper条件构造器添加自定义条件:

User user = new User();
user.setPerm("管理员");
userMapper.update(user,new QueryWrapper<User>().eq("pwd","12345"));

以上构造器生成的语句最终为:update user set perm = ‘管理员’ where pwd = 12345

常用条件构造方法

  • eq() =等于
  • gt() >大于
  • lt() <小于
  • like() LIKE ‘%值%’
  • orderby() 排序
  • having() 过滤
  • last() 在语句暴力拼接SQL(存在SQL注入的风险,不推荐使用。)
  • apply() 该方法可用于数据库函数 动态入参的params对应前面applySql内部的{index}部分.这样是不会有sql注入风险的,反之会有!
  • select() 设置查询字段

查看更多条件构造方法

六、逻辑删除

在做数据库的表记录删除时,我们常常使用的是逻辑删除,即改变某条记录的状态,从而对其进行限制。通常是给每条记录添加一个状态字段,使用0或1来表示他的某种状态(这里表示是否删除)。使用逻辑删除也避免了我们将重要的数据丢失的风险。
MP为我们提供一系列操作表的SQL语句自动实现,我们可以通过@TableLogic配置逻辑删除。
例:
在逻辑删除的字段上添加@TableLogic注解

 @TableLogic
 private Integer deleted;

配置逻辑删除的字段及状态值

# 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
mybatis-plus.global-config.db-config.logic-delete-field=deleted
#逻辑已删除值(默认为 1)
mybatis-plus.global-config.db-config.logic-delete-value=1
# 逻辑未删除值(默认为 0)
mybatis-plus.global-config.db-config.logic-not-delete-value=0

配置成功后使用MP的删除方法做的就是逻辑删除了

userMapper.deleteById(22);

注意:逻辑删除后的语句不会在被Mybatis-Plus方法查询出来,需要自定义SQL才能查看。

七、自动填充字段

在使用MP插入或新增数据时,我们可以给它添加一些默认的填充值。
例如下面自动填充对象的创建时间和更新时间
1.在需要自动填充的字段上添加@TableField注解,设置fill属性为FieldFill.INSERT插入时填充或FieldFill.INSERT_UPDATE插入或更新时填充。

//插入时自动填充时间
 @TableField(fill = FieldFill.INSERT)
 private Date createTime;
 //插入或更新时自动填充时间
 @TableField(fill = FieldFill.INSERT_UPDATE)
 private Date updateTime;

2.自定义一个元对象处理器接口的实现类并将它注入IOC容器中

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
        // 或者
        this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        // 或者
        this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "modify_time", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
        // 或者
        this.strictUpdateFill(metaObject, "modity_time", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        // 或者
        this.fillStrategy(metaObject, "modity_time", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
    }
}

Spring项目在配置文件中进行装配(在SpringBoot项目中可以省略下面步骤)

<!-- 这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合 -->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="plugins">
        <list>
            <!-- 注册分页插件 -->
            <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></bean>
        </list>
    </property>
    <property name="globalConfig" ref="globalConfig"/>
</bean>

<!--配置自动注入时间类-->
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
    <property name="metaObjectHandler">
        <bean class="com.zktr.handler.MyMetaObjectHandler"/>
    </property>
</bean>

八、MP的全局策略

  • 全局的主键策略配置
  • 表名是否使用驼峰转下划线命名,只对表名生效
  • 表格前缀(使实体类与表格名称对应)
<!--SpringMVC整合Mybatis-Plus-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
   <property name="dataSource" ref="dataSource"/>
     <property name="configLocation" value="classpath:mybatis-config.xml"/>
     <property name="plugins">
         <list>														
         <!-- 注册分页插件 -->																		           <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></bean>
         </list>
     </property>
     <property name="globalConfig" ref="globalConfig"/>
 </bean>
 
 <!--定义MybatisPlus的全局策略-->
 <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
     <property name="dbConfig" ref="dbConfig"/>
 </bean>

 <!--配置主键策略-->
 <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
     <!--使用数据库主键自增-->
     <property name="idType" value="AUTO"/>
     <!--驼峰式命名规则配置-->
     <property name="tableUnderline" value="true"/>
     <!--表名前缀-->
     <property name="tablePrefix" value="tab_"/>
 </bean>

九、分页插件 PaginationInnerInterceptor

SpringBoot 配置方式

@MapperScan("com.kuang.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        List<InnerInterceptor> list = new ArrayList<>();
        list.add(new PaginationInnerInterceptor(DbType.H2)); //分页插件
        interceptor.setInterceptors(list);
        return interceptor;
    }
}

测试

 @Test
 //分页插件
 void contextLoads() {
     Page<User> userPage = userMapper.selectPage(new Page<>(1, 2), null);
     for (User user : userPage.getRecords()) {
         //userPage.getRecords()查询数据列表
         System.out.println(user);
     }
 } 

十、乐观锁插件 OptimisticLockerInnerInterceptor

当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁:顾名思义什么乐观,它总是认为不会出现问题,无论干什么不去上锁!如果出现了问题,再次更新值测试!
悲观锁:顾名思义十分悲观,它总是认为总是出现问题,无论干什么都会上锁!再去操作!

乐观锁实现方式:先查询出带有version数据对象信息(非常重要),然后使用再在这个对象的基础上做修改。
例:
在版本字段加上注解

  @Version
  private Integer version;

在SpringBoot中配置插件

@MapperScan("com.kuang.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    /**
     * 新版
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

添加乐观锁的字段在修改之后version字段会自动递增。

userMapper.updateById(user);

乐观锁的可能存在的问题

  User user = userMapper.selectById(22);
  user.setName("牛牛");
  user.setPerm("1");

  //模拟另一个线程插队
  User user2 = userMapper.selectById(22);
  user2.setName("牛牛");
  user2.setPerm("2");

  userMapper.updateById(user2);
  userMapper.updateById(user);
  //最终结果显示只增加了一个版本,因为前一个被覆盖了。

十一、SQL执行分析插件 BlockAttackInnerInterceptor

该插件可用于针对 update 和 delete 语句 作用: 阻止恶意的全表更新删除
导入依赖

<!--执行 SQL性能分析依赖-->
<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.9.1</version>
</dependency>

使用SpringBoot的配置方式

@MapperScan("com.kuang.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        List<InnerInterceptor> list = new ArrayList<>();
		list.add(new BlockAttackInnerInterceptor());//攻击 SQL 阻断解析器,防止全表更新与删除
        interceptor.setInterceptors(list);
        return interceptor;
    }
}

编辑application.properties

spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8

添加spy.properties配置文件

#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

十二、自定义代码生成器MyCodeGenerator

在项目构建中有些步骤存在重复性,像是根据数据库表格创建一个Entity实体,接着在创建它相关的Mapper、Mapper.xml、Service、Controller等模块的文件。这些繁杂重复的步骤,对于我们的编程来说是无益的。为了解放我们双手,减少这些重复的劳动,MP给我们提供了代码发生器,用于帮助我们快速的构建项目结构。

要使用代码发生器,首先要导入以下依赖:

<!--代码生成器依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
</dependency>

<!--模板引擎 依赖-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.0</version>
</dependency>

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>

依赖导入完成后,需要我们自己编写发生器实现。以下代码可根据自己的需要自行调整,修改完成之后运行该程序即可。

public class MyCodeGenerator {
    public static void main(String[] args) {
        //1.全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");//当前项目目录
        globalConfig.setAuthor("wsl")             //作者
                .setActiveRecord(true)  //是否支持AR模式
                .setOutputDir(projectPath + "/src/main/java")  //生成路径
                .setFileOverride(false) //是否覆盖
                .setIdType(IdType.AUTO) //主键策略
                .setServiceName("%sService")    //%s用于生成的Service接口名称是否加上前缀 I
                .setBaseResultMap(true)
                .setBaseColumnList(true);

        //2.数据源配置
        DataSourceConfig dbConfig = new DataSourceConfig();
        dbConfig.setDriverName("com.mysql.cj.jdbc.Driver")  //设置数据库驱动
                .setUrl("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8")
                .setUsername("root").setPassword("123456")
                .setDbType(DbType.MYSQL);   //设置数据库类型

        //3.策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        // 自动填充配置
        ArrayList<TableFill> tableFills = new ArrayList<>();
        TableFill updateTime = new TableFill("updateTime", FieldFill.INSERT_UPDATE);
        tableFills.add(updateTime);
        strategyConfig.setInclude("blog") //生成的表
                .setCapitalMode(true) //全局大写命名
                .setNaming(NamingStrategy.underline_to_camel)   //数据库表隐射到实体的命名策略
                .setEntityLombokModel(true)      //自动lombok
                .setLogicDeleteFieldName("deleted") //逻辑删除
                .setVersionFieldName("version") //乐观锁
                .setControllerMappingHyphenStyle(true)
//                .setRestControllerStyle(true)
                .setTableFillList(tableFills);   //自动填充配置

        //4.包名策略配置
        PackageConfig pkConfig = new PackageConfig();
        pkConfig.setParent("com.kuang") //父包
                .setMapper("mapper")
                .setService("service")
                .setController("controller")
                .setEntity("pojo")
                .setXml("mapper")
                .setModuleName("blog");


        //5.整合配置
        AutoGenerator autoGenerator = new AutoGenerator();
        autoGenerator.setGlobalConfig(globalConfig)
                .setDataSource(dbConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(pkConfig);

        //6.执行
        autoGenerator.execute();
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值