MyBatis—Plus学习笔记

MyBatis—Plus学习笔记

1.MyBatis—Plus介绍

MyBatis—Plus 简称 MP,是一个Mybatis的增强工具,在原来Mybatis的基础上只做增加不做改变,为简化开发,提高效率而生

 

 愿景
 我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。

 

特性:

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

2.快速入门

创建Spring Initializr项目 勾选Lombok dev—tools web支持

1.完善Maven依赖

SpringBoot导入的数据库连接MySQL是8.0版本,但版本向下兼容

 

 

 <!--        数据库连接驱动-->
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
         </dependency>
 <!--        MyBatis_Plus-->
         <dependency>
             <groupId>com.baomidou</groupId>
             <artifactId>mybatis-plus-boot-starter</artifactId>
             <version>3.0.5</version>
         </dependency>

第二次项目启动出错 导入

 <!--            解决第二次运行出错-->
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-resources-plugin</artifactId>
                 <version>3.1.0</version>
             </plugin>

2.创建数据库以及对应的表

 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)
 );
 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');
 -- 真实开发中,version(乐观锁)、deleted(逻辑删除)、gmt_create、gmt_modified

3.配置properties 连接

 #Mysql 5
 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?userSSL=true;useUnicode=true;characterEncoding=UTF-8;serverTimezone=UTC
 spring.datasource.username=root
 spring.datasource.password=123456

4.使用MyBatis—Plus

传统方法 pojo-Mapper-Mapper.xml-controller

现:

1.pojo

 @Data
 @AllArgsConstructor
 @NoArgsConstructor
 public class User {
     private Long id;
     private String name;
     private Integer age;
     private String email;
 }

2.Mapper接口

 @Repository //代表是持久层
 //在对应的Mapper上继承基本类  BaseMapper
 public interface UserMapper extends BaseMapper<User> {
     //所有的CRUD已经编写完成
 }
  • 注意点,我们需要在主启动类上去扫描我们的mapper包下的所有接口

    @MapperScan("com.heng.mapper")

3.测试

 @SpringBootTest
 class MybatisPlusApplicationTests {
     // 继承了BaseMapper,所有的方法都来自己父类
     // 我们也可以编写自己的扩展方法!
     @Autowired
     private UserMapper userMapper;
     @Test
     void contextLoads() {
         // 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
         // 查询全部用户
         List<User> users = userMapper.selectList(null);
         users.forEach(System.out::println);
     }
 }

3.配置日志

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

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

4.CRUD拓展

4.1、主键生成策略

insert插入 默认ID_WORKER全局唯一id

@Test
    //插入测试
    public void insert(){
        User user = new User();
        user.setAge(12);
        user.setName("wanghang");
        int count = userMapper.insert(user);//帮我们自动生成ID
        System.out.println(count);//受影响的行数
        System.out.println(user);//ID自动回填
    }

此时我们没有设置id值,MP会自动给我们生成一个id,此id全局唯一

 

主键生成策略

雪花算法

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

主键自增

 

我们需要配置主键自增:

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

  2. 数据库id字段一定要自增!

  3. 再次测试插入即可

@TableId 源码

 

 

4.2、更新操作

所有的sql都是动态的

此时设置什么值,就会更新什么值

@Test
    //测试更新
    public void update(){
        // 通过条件自动拼接动态sql
        User user = new User();
        user.setId(1l);
        user.setName("xlh");
        user.setAge(181);
        user.setEmail("32933424921421@qq.com");
        //注意:updateById 但是参数是一个 对象!
        int count = userMapper.updateById(user);
    }

4.3、自动填充

阿里巴巴开发手册中规定:所有数据库表中gmt_create、gmt_modified几乎所有的表都需要配置上,而且要自动化;

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

1.在表中新增字段 creat_time,update_time

2.在实体类中 增加这个两个属性 (对应的为creatTime,updateTime)驼峰命名规则法

3.修改数据库表结构中

方式二:代码级别

1.删除数据库中的默认值,更新操作

2.在实体类中属性增加注解

注意:

id的注解是 @TableId

字段的注解是 @TableField

    //字段添加内容
		//增加
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
		//增加更新
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

 

3.编写一个控制器处理即可

@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);
    }
}

4.测试插入

5.观察更新时间和插入时间即可

4.4、乐观锁

乐观锁和悲观锁

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

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

乐观锁实现方式

  • 取出记录时,获取当前version

  • 更新时,带上这version

  • 执行更新时,set version = new version where version = oldversion

  • 如果version不对,就更新失败

乐观锁:1、先查询,获得版本号 version = 1
-- A
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
-- B 线程抢先完成,这个时候 version = 2,会导致 A 修改失败!
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1

测试MP的乐观锁插件

1.给数据库中添加version字段

2.我们给实体类中对应的字段

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

3.注册组件

// 扫描我们的 mapper 文件夹
@MapperScan("com.kuang.mapper")
@EnableTransactionManagement
@Configuration // 配置类
public class MyBatisPlusConfig {
    // 注册乐观锁插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

4.测试乐观锁

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

    // 测试乐观锁失败!多线程下
    @Test
    public void testOptimisticLocker2(){
        // 线程 1
        User user = userMapper.selectById(1L);
        user.setName("kuangshen111");
        user.setEmail("24736743@qq.com");
        // 模拟另外一个线程执行了插队操作
        User user2 = userMapper.selectById(1L);
        user2.setName("kuangshen222");
        user2.setEmail("24736743@qq.com");
        userMapper.updateById(user2);
        // 自旋锁来多次尝试提交!
        userMapper.updateById(user); // 如果没有乐观锁就会覆盖插队线程的值!
    }

4.5、查询操作

提供了根据id查询,批查询,Map查询

//根据id进行查询
    @Test
    public void testQueryUserById(){
        User user = userMapper.selectById(1L);
        System.out.println(user);
    }

    @Test
    //测试批量操作
    public void testQueryUserBatchIds(){
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    //按照条件查询之一使用Map
    public void testQueryUserByMap(){
        Map<String,Object> map = new HashMap<>();
        map.put("name","邢垆恒");
        List<User> users = userMapper.selectByMap(map);
        for (User user : users) {
            System.out.println(user);
        }
    }
    

4.6、分页查询

分页在网站上使用的非常多

1、原始的limit继续分页

2、pageHepler 第三方插件

3、MP也内置了分页插件

使用

拦截器的实质就时拦截器

1.配置拦截器

  @Bean
    //导入分页插件
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }

2.直接使用Page对象即可

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

    for (User record : page.getRecords()) {
        System.out.println(record);
    }

    System.out.println(page.getTotal());
}

4.7、删除操作

//删除查询
@Test
public void testDeleteById(){
    int i = userMapper.deleteById(1448186516407885837L);
    if (i>0){
        System.out.println("删除成功");
    }
}

//批量删除
@Test
public void testDeleteByBatchs(){
  userMapper.deleteBatchIds(Arrays.asList(1448186516407885834L,1448186516407885832L));
}
//通过map删除
@Test
public void deleteByMap(){
    HashMap<String, Object> map = new HashMap<>();
    map.put("age",10);
    userMapper.deleteByMap(map);
}

4.8、逻辑删除

物理删除:从数据库中直接移除

逻辑删除:从数据库中没有被移除,二十通过一个变量让他失效.deleted = 0=>deleted = 1

管理员可以查看到被删除的记录,以防记录的丢失,类似于回收站,测试

1.在数据表中增加一个deleted字段 设置默认值为0

2.在实体类中添加属性

注意:不能使用delete 这是一个关健字会导致失效

//逻辑删除字段
    private Integer del;

3.添加逻辑删除的配置

#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

4.测试

逻辑删除改变的是delete的值,在查询的时候会动态拼接deleted=0,改变了值就查询不到了

 

再次查询查询不到

 

4.9、性能分析插件

在平时开发中遇到的慢sql,我们可以通过MQ进行测试

作用:性能分析拦截器,用于输出每条sql语句及其执行时间

MP也提供了性能分析插件,如果超过了这个时间就停止运行

MP3.2以后版本移除了性能分析插件可以通过druid执行sql的性能分析。

4.10、条件构造器

重要

Wrapper 我们写了一些复杂的sql就可以使用它来替代 封装好了很多的sql操作

测试

@SpringBootTest
public class WrapperTest {

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

    @Test
    public void test2(){
        //查询名字 李昕祚
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name","李昕祚");
        System.out.println(userMapper.selectOne(wrapper));
    }
    @Test
    public void test3(){
        //查询 between  and
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("age","18","28");//区间
        Integer count = userMapper.selectCount(queryWrapper);
        System.out.println(count);
    }

    @Test
    public void testLike(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //查询名字中不包含e,且邮箱是以e开头的用户
        queryWrapper.notLike("name","e").likeRight("email","e");
        List<Map<String, Object>> mapList = userMapper.selectMaps(queryWrapper);
        mapList.forEach(System.out::println);
    }

    @Test
    public void testSon() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("id", "select id from user where id < 3");
        List<Object> users = userMapper.selectObjs(queryWrapper);
        users.forEach(System.out::println);
    }
    @Test
    public void testOrderBy(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    }
}

5.代码生成工具

导入模板引擎

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

public class HengCode {

    @Test
    public void test() {
        //1.需要构建一个代码生成器 对象
        AutoGenerator mpg = new AutoGenerator();
        //全局配置策略
        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("%sService");
        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?userSSL=true;useUnicode=true;characterEncoding=UTF-8;serverTimezone=UTC");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
        //3.包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("test");
        pc.setParent("com.heng");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");

        mpg.setPackageInfo(pc);

        //4.策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        //要映射的表名称
        strategyConfig.setInclude("teacher");
        //下划线转托名命名规则
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        //自动Lombok
        strategyConfig.setEntityLombokModel(true);
        //设置逻辑删除的字段名称
        strategyConfig.setLogicDeleteFieldName("del");
        //自动填充策略
        TableFill gmtCreate = new TableFill("creat_time", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("creat_time", FieldFill.INSERT);

        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtModified);
        tableFills.add(gmtCreate);
        strategyConfig.setTableFillList(tableFills);

        //乐观锁
        strategyConfig.setVersionFieldName("version");
        strategyConfig.setRestControllerStyle(true);
        strategyConfig.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategyConfig);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值