MyBatisPlus

只要学不死,就往死里学。

1、概述

  • MybatisPlus可以节省大量的时间,偷懒,所有的CRUD代码都可以自动完成
  • JPA、tk-mapper、MybatisPlus
  • 在mybatis的基础上,只做增强,不做改变、简化开发、提高效率

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、快速入门

https://baomidou.com/guide/quick-start.html

1、导入依赖

<!--mybatis-plus 是自己开发的,并非官方的-->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.13</version>
</dependency>
<!--mybatis-plus 是自己开发的,并非官方的-->
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>3.0.5</version>
</dependency>
  • 提示:mybatis-plus 可以节省大量的代码,尽量不要同时导入mybatis和mybatis-plus

2、数据库连接配置(application.properties)

# 数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2b8
  • serverTimezone=GMT%2b8:北京时间东八区(%2b8不设置会少8个小时)

3、传统是pojo->mapper(连接mybatis,配置mapper.xml文件)->service-controller

  • 使用了mybatis-plus就不需要配置mapper.xml文件了

  • UserMapper.java

//在对应的mapper继承BaseMapper
//把泛型设置成自己需要的,基本的增删改查就完成了,也不需要配置mapper.xml文件了
@Repository
public interface UserMapper extends BaseMapper<User> {
}
  • 注意:需要在主启动类加扫描注解@MapperScan("com.lvboaa.mapper")

4、测试

@SpringBootTest
class MybatisPlusApplicationTests {

    //继承了BaseMapper,所有的方法都来自父类
    //也能编写自己的扩展方法(难的,简单的都有)
    @Autowired
    UserMapper userMapper;
    @Test
    void contextLoads() {
        //查询全部用户
        //参数是Wrapper,条件构造器,这里先不用 用null
        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println);
    }

}

思考

  • SQL是谁写的?mybatis-plus
  • 方法是谁写的?mybatis-plus

4、CRUD扩展

4.1、日志

application.properties

# 日志
# 控制台输出,可使用log4j或其他的,需要导入依赖
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4.2、插入操作和主键生成策略

@Test
void testInsert(){
    User user = new User();
    user.setName("lvbo");
    user.setAge(3);
    user.setEmail("1212121@qq.com");
    userMapper.insert(user);
}
  • pojo实体类的id为Long类型时,插入不需要设置id,mybatis-plus会自动根据雪花算法设置id
  • 数据库主键生成策略:uuid、自增、雪花算法(这儿的,一般用于分布式)、redis、zookeeper

雪花算法

  • Twitter的SnowFlake算法,64 个 bit 中,其中 1 个 bit 是符号位(永远是0),然后用其中的 41 bit 作为毫秒数,用 10 bit 作为工作机器 id,12 bit 作为序列号。

  • 全局唯一id配置(默认是这个)@TableId(type = IdType.ID_WORKER),实现算分是雪花算法

配置自增

  • 设置属性注解@TableId(type = IdType.AUTO)
  • 设置字段为自增字段

类型解释

public enum IdType {
    AUTO(0), //自增
    NONE(1), //未设置主键
    INPUT(2), //手动输入,必须自己输入id
    ID_WORKER(3), //全局唯一id,数字
    UUID(4), //全局唯一uuid
    ID_WORKER_STR(5);  //全局唯一id,字符串
}

4.3、更新测试

@Test
void testUpdate(){
    User user = new User();
    user.setId(6l);
    user.setName("lvbo1");
    userMapper.updateById(user);
}
  • 会根据设置参数自动拼接动态SQL

4.4、自动填充

创建时间(gmt_create)、修改时间(gmt_modified)每张表必备,需要自动化更新(阿里巴巴手册)
在这里插入图片描述

方式一:数据库级别(工作中不建议使用)

  1. 在数据库中增加字段:create_time、update_time
  2. 配置创建时间默认值和更新时间更新时修改

方式二:代码级别

  • 在数据库中增加字段:create_time、update_time
  • 在实体类为字段添加注解
//在插入时填充字段
@TableField(fill = FieldFill.INSERT)
private Date createTime;
//插入和删除都填充字段
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
  • 编写处理器处理注解
@Component
@Slf4j
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("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill..........");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}
  • 在执行添加或者更新操作时Mybatis-Plus会使用反射自动装配这两个属性

4.5、乐观锁

主要是处理并发事件
https://www.jianshu.com/p/d2ac26ca6525

乐观锁

  • 十分乐观,总是认为不会出现问题,无论干什么都不加锁
  • 乐观锁比较适用于读多写少的情况(多读场景)
  • 乐观锁不会刻意使用数据库本身的锁机制,而是依据数据本身来保证数据的正确性
  • 直到提交的时候才去锁定,所以不会产生任何锁和死锁。
  • 就是更新数据的时候根据一个字段去判断是否被其他人修改了

悲观锁

  • 十分悲观,总是认为会出现问题,无论干什么都加锁
  • 悲观锁比较适用于写多读少的情况(多写场景)
  • 悲观锁主要分为共享锁和排他锁:
    • 共享锁:读锁,简称S锁。共享锁就是多个事务对于同一数据可以共享一把锁,都能访问到数据,但是只能读不能修改。
    • 排他锁:写锁,简称X锁。排他锁就是不能与其他锁并存,如果一个事务获取了一个数据行的排他锁,其他事务就不能再获取该行的其他锁,包括共享锁和排他锁,但是获取排他锁的事务是可以对数据行读取和修改。
  • 并发控制采取“先取锁再访问”的策略,为数据处理的安全提供了保证,降低了并行性,造成了额外的开销,增加了产生死锁的概率

MybatisPlus实现乐观锁
在这里插入图片描述

当要更新一条记录的时候,希望这条记录没有被别人更新

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败
    在这里插入图片描述

测试Mybatis-Plus乐观锁插件

  • 在数据库添加version字段
  • 在实体类添加version属性
  • 配置类
@MapperScan("com.lvboaa.mapper")
//事务自动福安里
@EnableTransactionManagement
//配置类
@Configuration
public class MybatisPlusConfig {

    //注册乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }
}
  • 测试
//测试乐观锁 更新成功
@Test
void testOpt1(){
    User user = userMapper.selectById(1l);
    user.setName("lvbo");
    userMapper.updateById(user);
}
//测试乐观锁 更新失败
@Test
void testOpt2(){
    //线程1
    User user = userMapper.selectById(1l);
    user.setName("lvbo1");
    //模拟线程二执行了插队操作
    User user1 = userMapper.selectById(1l);
    user1.setName("lvbo2");
    userMapper.updateById(user1);
    
	//可以通过自旋锁尝试提交
    userMapper.updateById(user);//如果没有乐观锁会覆盖线程2的值
}
  • 日志结果:可以发现执行修改操作会匹配version字段来实现乐观锁思想
    在这里插入图片描述

4.6、查询 || 删除也一样有这些方法

//按id查询 userMapper.selectById(1l);
//测试批量查询
@Test
void testSelectBatchIds(){
    List<User> userList = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    userList.forEach(System.out::println);
}
//条件查询
@Test
void testSelectByMap(){
    HashMap<String, Object> map = new HashMap<>();
    map.put("name","lvbo2");
    List<User> users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}

4.7、分页查询

  • 原始使用limit进行分页
  • pageHelper分页插件
  • mybatis-plus也有分页插件

配置

  • 配置拦截器,在MybatisPlusConfig.java配置类中
//配置分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
    return new PaginationInterceptor();
}
  • 测试
//分页测试
@Test
void testPage(){
    //首先会执行  SELECT COUNT(1) FROM user
    //参数1:当前页  参数2:页面大小
    Page<User> page = new Page<>(2, 5);
    userMapper.selectPage(page,null);

    page.getRecords().forEach(System.out::println);
}

4.8、逻辑删除

物理删除:直接删除数据库中的记录
逻辑删除:数据库中没有被移除,通过一个字段让它失效!deleted=0 ==> deleted=1

比如说管理员可以查看被删除的记录,类似于回收站

实现

  • 添加deleted字段
    在这里插入图片描述
  • 配置实体类属性
@TableLogic
private Integer deleted;
  • 配置配置类和application.properties
//逻辑删除组件
@Bean
public ISqlInjector sqlInjector(){
    return new LogicSqlInjector();
}
# 逻辑删除
# 删除的值
mybatis-plus.global-config.db-config.logic-delete-value=1
# 没删除的值
mybatis-plus.global-config.db-config.logic-not-delete-value=0
  • 执行删除操作测试
    • 发现记录未被删除,执行的更新操作,更新了deleted字段,实现逻辑删除
    • 再执行查询操作的时候会自动把deleted=0给拼接进条件子句想,相当于被删除了
//删除
@Test
void testDelete(){
    userMapper.deleteById(1L);
}

4.9、性能分析插件

遇到一些慢SQL执行超过一定时间就停止运行,在工作中十分常用(不允许用户等待)

作用

  • 分析拦截器:用于输出sql语句和执行时间

实现

  • 配置组件(MybatisPlusConfig.java)
//SQL效率插件
@Bean
@Profile({"dev","test"}) //设置什么环境开启,保证效率(pro生产环境)
public PerformanceInterceptor performanceInterceptor(){
    PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
    performanceInterceptor.setMaxTime(100);//ms 设置sql执行的最大时间,如果超过了就不执行
    performanceInterceptor.setFormat(true);//设置sql输出格式
    return performanceInterceptor;
}
  • 需要配置spring 的运行环境spring.profiles.active=dev
  • 在执行sql语句中,如果超过了这个时间就会抛出异常

4.10、条件构造器Wrapper

测试

@SpringBootTest
public class WrapperTest {
    @Autowired
    UserMapper userMapper;
    @Test
    void test1() {
        //查询name不为空、email不为空、年龄大于等于12的
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .isNotNull("name")
                .isNotNull("email")
                .ge("age",3);//大于等于
        List<User> userList = userMapper.selectList(wrapper);
        userList.forEach(System.out::println);
    }
    @Test
    void test2() {
        //查询name为lvbo的
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name","lvbo");
        User user = userMapper.selectOne(wrapper);
        System.out.println(user);
    }

    @Test
    void test3() {
        //查询年龄在20~30之间的
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("age",20,30);
        //使用selectCount(wrapper) :表示计数,多少行
        List<User> userList = userMapper.selectList(wrapper);
        userList.forEach(System.out::println);
    }

    @Test
    //模糊查询
    void test4() {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .notLike("name","e")
                .likeRight("email","t");// t%
        List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
        maps.forEach(System.out::println);
    }

    @Test
    //子查询
    void test5() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.inSql("id","select id from user where id < 3");
        List<Object> objects = userMapper.selectObjs(wrapper);
        objects.forEach(System.out::println);
    }

    @Test
    //排序
    void test6() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        List<User> list = userMapper.selectList(wrapper);
        list.forEach(System.out::println);
    }
}

4.11、代码自动生成器

导入依赖

<!--velocity-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.0</version>
</dependency>

实现:KuangCode.java

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;

/**
 * @author lvbo
 * @date 2021年 01月26日 18:56:16
 */
//代码自动生成器
public class KuangCode {
    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"); //获取到项目java目录
        gc.setAuthor("狂神说");
        gc.setOpen(false);
        gc.setFileOverride(false); // 是否覆盖
        gc.setServiceName("%sService"); // 去Service的I前缀 为UserService
        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?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2b8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
        //3、包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("mybatis");
        pc.setParent("com.lvboaa");
        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 gmtModified = new TableFill("gmt_modified",FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate);
        tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);
        // 乐观锁
        strategy.setVersionFieldName("version");

        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.execute(); //执行
    }
}

自动生成代码
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值