MybatisPlus学习及拓展


活动地址:CSDN21天学习挑战赛

目录

特性

快速入门

步骤

日志配置

CRUD拓展

插入数据

主键生成策略

更新数据

自动填充

乐观锁

查询数据

分页查询

删除数据

逻辑删除数据


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

特性

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

  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求,简单的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 操作智能分析阻断,也可自定义拦截规则,预防误操作

快速入门

使用第三方组件:

1.导入对于依赖

2.研究如何配置

3.代码编写

4.提高拓展技术

步骤

1.创建数据库Mybatis_plus

2.创建User表

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)
);
-- 真实开发,version(乐观锁),deleted(逻辑删除)
DELETE FROM user;
​
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');
​

3.编写项目,初始化项目,使用StringBoot初始化

4.导入依赖

   
 <dependencies>
<!--        数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
<!--        lommbok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
<!--        mybatis—plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
​
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
​
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

注意:mybatis-plus可以节省大量代码,尽量不要同时导入mybatis和mybatis-plus

5.连接数据库

#mysql 8 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456

6.使用Mybatis的时候(pojo-dao(链接mybatis,配置Mapper.xml文件)-service-controller)

6.使用mybatis-plus之后

  • pojo

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

  • mapper接口

    @Mapper
    //@Repository
    // 在对于的Mapper上面继承基本的类baseMapper
    public interface UserMapper extends BaseMapper<User> {
        //所有的CRUD操作已近完成,不需要以前一样编写大堆配置文件
    }

  • 在启动主类上去扫描我们Mapper包下的所有接口 @MapperScan("com.kyf.mapper")

  • 测试

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

问题?

sql谁写的 Mybatis-plus准备好了

方法哪里来的 Mybatis-plus准备好了

日志配置

查看使用的sql日志打印

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

CRUD拓展

插入数据

@Test
public void testInsert( ) {
    User user = new User();
    user.setName("张三");
    user.setAge(5);
    user.setEmail("aaa");
​
    int insert = userMapper.insert(user);//会帮我们自动生成id
    System.out.println(insert);//返回受影响的行数
}

数据库插入的id默认值为全局的唯一id 

主键生成策略

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

主键自增

我们需要主键自增:

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

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

3.再次插入数据即可

其他几个类型的解释

AUTO(0),  //主键自增
NONE(1),    // 未设置主键
INPUT(2), // 手动输入
ASSIGN_ID(3), // 分配ID
ASSIGN_UUID(4); //分配UUID

更新数据

@Test
public void testUpdate() {
    User user = new User();
    user.setId(1559447191389528065L);
    user.setName("张三aaa");
    user.setAge(12);
    user.setEmail("aaabbb");
    int i = userMapper.updateById(user);
    System.out.println(i);
}

可以动态拼接sql语句

自动填充

创建时间、修改时间!这些操作一般都是自动化完成的。

一般情况下,我们所有的表要包括: gmt_create 和gmt_modified这俩个数据,并且需要自动化!

方法一:数据库级别

1.在表里面建俩个字段create_time和update_time

类型长度默认值注释
create_timedatetime0CURRENT_TIMESTAMP创建时间
update_timedatetime0CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP修改时间

2.然后同步实体类。 

private Date createTime;
private Date updateTime;

3.更新查看结果

方法二:代码方式

1.先把数据库表的默认值和更新操作删除!

2.实体类属性增加注释

@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.测试更新,观察时间

插入的时间和显示时间差8个时区的解决方式

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true&allowPublicKeyRetrieval=true

乐观锁

面试常常遇到被问到乐观锁、悲观锁!

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

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

乐观锁机制

乐观锁实现方式:

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

  • 更新时,带上这个 version

  • 执行更新时, set version = newVersion where version = oldVersion

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

乐观锁 1.先查询,获取当前的version = 1 
​
--A
​
update user set name='张三' ,version = version+1
​
where id = 2 and version = 1
​
--B 线程抢先完成,这个时候Version=2,会导致A线程修改失败
​
update user set name='张三' ,version = version+1
​
where id = 2 and version = 1

测试 mybatisplus的乐观锁插件

1.先给数据库表加

 

2.实体类

@Version
private Integer version;

3.注册组件

@MapperScan("com.kyf.mapper")
@EnableTransactionManagement
@Configuration // 配置类
public class MyBatisPlusConfig {
​
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

4.测试

成功情况

    @Test
    public void testOptimisticLocker(){
//        先查
        User user = userMapper.selectById(1L);
//        改变值
        user.setName("zhangsan");
        user.setAge(18);
//        修改
        userMapper.updateById(user);
    }

 

失败情况

    @Test
    public void testOptimisticLocker2(){
//        先查一
        User user = userMapper.selectById(1L);
        user.setName("zhangsan111");
        user.setAge(18);
//        模拟另一个线程
        User user1 = userMapper.selectById(1L);
        user1.setName("zhangsan222");
        user1.setAge(18);
        userMapper.updateById(user1);
​
        //自旋锁操作
        userMapper.updateById(user);//看有没有将值覆盖
    }

user没有将user1的值覆盖

 

查询数据

//测试查询
@Test
public void testSelectById(){
    User user = userMapper.selectById(1L);
    System.out.println(user);
}
​
//测试批量查询
@Test
public void testSelectBatchIds(){
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    users.forEach(System.out::println);
}
​
//测试条件查询,map操作
@Test
public void testSelectByMap(){
    HashMap<String,Object> map = new HashMap<>();
    map.put("name","Jack");
    map.put("age",20);
    List<User> users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}

分页查询

1.原始的limit分页

2.第三方插件pageHelper分页

3.Mybatisplus只带分页

如何使用

1.配置拦截器组件即可

//  分页插件
@Bean
public PaginationInnerInterceptor paginationInnerInterceptor(){
    return new PaginationInnerInterceptor();
}//高版本Boot会提示版本过低
​
@Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
   //数据库类型是MySql,因此参数填写DbType.MYSQL
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
 

2.直接使用Page对象

    @Test
    public void testPage(){
        //参数一:哪一页
        //参数二:数据数量
        Page<User> page = new Page<>(1,5);
        userMapper.selectPage(page, null);
        page.getRecords().forEach(System.out::println);
    }

 

删除数据

根据id删除

//测试删除
@Test
public void testDeleteById(){
    userMapper.deleteBatchIds(Arrays.asList(1559450872163930114L,1559450959208284162L));
}
//测试条件删除使用Map
@Test
public void TestDeleteMap(){
   HashMap<String,Object> map =  new HashMap<>();
   map.put("name","张三aaa");
   map.put("age",20);
   userMapper.deleteByMap(map);
}

逻辑删除数据

物理删除:从数据库删除

逻辑删除:数据库中没有删除,通过某一个变量让数据失效!delete==》0?==》1

1.先在数据库中加入delete字段

2.实体类中加属性注释

@TableLogic
private Integer delete;

3.添加逻辑删除组件

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'delete=1 WHERE id=1 AND delete=0' at line 1

报这个错误需要更改数据库delete字段名字,和实体类参数名字

添加配置

mybatis-plus.global-config.db-config.logic-delete-field=flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
    @Test
    public void testDeleteById(){
        userMapper.deleteById(1L);
//        userMapper.deleteBatchIds(Arrays.asList(1559450872163930114L,1559450959208284162L));
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值