SpringBoot项目集成Mybatis-plus

1、Mybatis-plus简介

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

2、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 操作智能分析阻断,也可自定义拦截规则,预防误操作

3、springboot项目使用mybatis-plus

1)首先在pom.xml文件中导入相关依赖

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

2) 修改properties配置文件

# 数据源  使用的是spring中自带的datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/springboot

# 打印sql语句日志
logging.level.com.lyq.springboot.dao=debug

# 扫描mapper的xml文件
mybatis-plus.mapper-locations=classpath:mapper/*.xml

3) 创建实体类对象

@Data
@EqualsAndHashCode(callSuper = false)
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键ID
     * type = IdType.AUTO 设置成主键自动递增,必须保持数据库表的主键设置为递增
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 邮箱
     */
    private String email;

    /**
     * 逻辑删除,对数据库表中的字段修改状态
     */
    @TableLogic
    private Integer deleted;

    /**
     * 数据的创建时间
     * fill = FieldFill.INSERT 表示执行insert语句的时候,自动更新时间
     */
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    /**
     * 对数据的修改时间
     * fill = FieldFill.INSERT_UPDATE 表示执行insert和update语句的时候,自动更新时间
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
}

@TableId注解是添加在主键字段上的,其中的value属性,值要与数据库表中的主键字段保持一致;type属性,值可以指定主键的类型,如下图所示;
在这里插入图片描述若主键类型指定为AUTO,表示主键自增;但需要注意的是,数据库表的主键也要设置成为自增类型
在这里插入图片描述若主键类型指定为NONE、INPUT类型,则是需要人为输入主键;
ASSIGN_ID是针对int类型的主键,底层是雪花算法;
ASSIGN_UUID是针对String类型的主键,使用UUID生成主键,去除生成的- ;

4)创建dao接口

public interface UserMapper extends BaseMapper<User> {

}

创建的接口要继承BaseMapper,这个类所在的包为com.baomidou.mybatisplus.core.mapper.BaseMapper;
其中的泛型为接口对应的实体类

5)在主启动类上添加注解@MapperScan

@SpringBootApplication
@MapperScan("com.lyq.springboot.dao")
public class SpringbootMybatisplusApplication {

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

}

@MapperScan指定自己的dao包的路径

4、对Mapper CRUD接口的简介

在这里插入图片描述

1)BaseMapper 接口内置增删改查方法的简介与使用

1.1)Insert

// 插入一条记录
int insert(T entity);

在这里插入图片描述

1.2)Delete

// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

在这里插入图片描述

1.2.1) 逻辑删除的使用

在这里插入图片描述

①在数据库表中添加字段deleted,设置为int类型

在这里插入图片描述

②在实体类中添加属性,

方式一:属性添加注解@TableLogic

/**
     * 逻辑删除,对数据库表中的字段修改状态
     */
    @TableLogic
    private Integer deleted;

方式二:配置文件

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag  # 全局逻辑删除的实体字段名
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
③常见的问题

新增了逻辑删除字段,所以在执行新增操作的时候,逻辑删除字段的值赋予可以有三种方式解决

  1. 字段在数据库定义默认值(推荐)
  2. insert 前自己 set 值
  3. 使用自动填充功能

1.3) Update

// 根据 whereWrapper 条件,更新记录
int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper<T> whereWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);

在这里插入图片描述

1.3.1)自动填充功能简介与使用

①在数据库中创建两个字段,分别为createTime创建时间,updateTime修改时间
在这里插入图片描述②在实体类上添加属性,并在属性上添加注解

 /**
     * 数据的创建时间
     * fill = FieldFill.INSERT 表示执行insert语句的时候,自动更新时间
     */
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    /**
     * 对数据的修改时间
     * fill = FieldFill.INSERT_UPDATE 表示执行insert和update语句的时候,自动更新时间
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;

③自定义实现类 MyMetaObjectHandler

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 执行添加操作的时候,执行此方法
     * 与实体类中的注解 @TableField(fill = FieldFill.INSERT) 联合使用
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

    }

    /**
     * 执行修改操作的时候,执行此方法
     * 与实体类中的注解 @TableField(fill = FieldFill.UPDATE) 联合使用
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        // 起始版本 3.3.0(推荐使用)
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

    }
}

注意事项

  • 填充原理是直接给entity的属性设置值!!!
  • 注解则是指定该属性在对应情况下必有值,如果无值则入库会是null
  • MetaObjectHandler提供的默认方法的策略均为:如果属性有值则不覆盖,如果填充值为null则不填充
  • 字段必须声明TableField注解,属性fill选择对应策略,该声明告知Mybatis-Plus需要预留注入SQL字段
  • 填充处理器MyMetaObjectHandler在 Spring Boot 中需要声明@Component或@Bean注入
  • 要想根据注解FieldFill.xxx和字段名以及字段类型来区分必须使用父类的strictInsertFill或者strictUpdateFill方法
  • 不需要根据任何来区分可以使用父类的fillStrategy方法

1.4) Select

// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 查询(根据ID 批量查询)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

在这里插入图片描述分页查询
①创建分页的配置类

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

}

② 测试

@Resource
    private UserMapper userMapper;

    /**
     * 使用分页插件,进行分页查询
     */
    @Test
    void contextLoads() {
        Page page = new Page<User>(1,4);
        Page selectPage = userMapper.selectPage(page, null);
        System.out.println(selectPage.getRecords());
    }

SQL语句执行日志
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值