idea mybatisplus 插件_MyBatisPlus 快速上手

1.简介

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。详情见官网,关键之处在特性。

润物无声只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑。

效率至上
只需简单配置,即可快速进行 CRUD 操作,从而节省大量时间。

丰富功能
热加载、代码生成、分页、性能分析等功能一应俱全

2.框架结构

d01fbf55fe8507919ca03cf5474f1955.png

3.快速配置环境

导入依赖

com.baomidoumybatis-plus-boot-starter3.3.1mysqlmysql-connector-javaruntimeorg.projectlomboklomboktrue        

配置application.properties文件,yml会更加合适

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8spring.datasource.username=rootspring.datasource.password=123456

在主类中添加@MapperScan注解,也可以自己写一个MP的配置类

@MapperScan("com.springboot.mybatis_plus.mapper")@SpringBootApplicationpublic class MybatisPlusApplication {public static void main(String[] args) {        SpringApplication.run(MybatisPlusApplication.class, args);    }}

4.测试CRUD

随便写一个实体类测试一下

@Datapublic class User {private Long id;private String name;private Integer age;private String email;}

创建mapper包,编写Mapper接口UserMapper

//IDEA在 userMapper 处报错,因为找不到注入的对象,因为类是动态创建的,但是程序可以正确的执行。//为了避免报错,可以在 dao 层 的接口上添加 @Repository @Repositorypublic interface UserMapper extends BaseMapper {//继承的BaseMapper类中有许多现成的CRUD方法,非常好用}

接下来就可以进行注入测试了

测试CRUD

@SpringBootTestclass MybatisPlusApplicationTests {@Autowiredprivate UserMapper userMapper;@Testvoid testSelectList() {//UserMapper 中的 selectList() 方法的参数为 MP 内置的条件封装器 Wrapper//所以不填写就是无任何条件        List users = userMapper.selectList(null);        users.forEach(System.out::println);//查询指定id        User user = userMapper.selectById(1);        System.out.println(user);    }@Testpublic void testInsert(){        User user = new User();        user.setName("ly").setAge(22).setEmail("578104130@qq.com");int insert = userMapper.insert(user);        System.out.println("影响的行数" + insert);        System.out.println("id" + user);    }@Testpublic void testUpdate(){        User user = new User();        user.setId((long) 7).setName("wxy");int insert = userMapper.updateById(user);        System.out.println("影响的行数" + insert);        System.out.println("id" + user);    }@Testpublic void testDeleteById(){int result = userMapper.deleteById(5L);        System.out.println(result);    }}

查看sql日志

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

5.MP的特性

1) 主键策略

MyBatis-Plus默认的主键策略是:ASSIGN_ID (使用了雪花算法),具体还有哪些主键策略,可以点进去IdType查看

@TableId(type = IdType.ASSIGN_ID)private String id;

AUTO 自增策略,需要在创建数据表的时候设置主键自增,实体字段中配置 @TableId(type = IdType.AUTO)

@TableId(type = IdType.AUTO)private Long id;

要想影响所有实体的配置,可以设置全局主键配置

#全局设置主键生成策略mybatis-plus.global-config.db-config.id-type=auto

2) 自动填充

实体类添加字段并添加自动填充注解

//自动填充@TableField(fill = FieldFill.INSERT)private Date createTime;//@TableField(fill = FieldFill.UPDATE)@TableField(fill = FieldFill.INSERT_UPDATE)    private Date updateTime;

实现元对象处理器接口

@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {//首次插入的时候为两个字段赋值this.setFieldValByName("createTime", new Date(), metaObject);this.setFieldValByName("updateTime", new Date(), metaObject);    }@Overridepublic void updateFill(MetaObject metaObject) {//更新的时候只需要修改updateTimethis.setFieldValByName("updateTime", new Date(), metaObject);    }}

3) 乐观锁插件

锁大家一定不陌生,当不同的用户同时读写同一份数据的时候,就会出现很多问题。锁分为两种,悲观锁(用户一处理数据就封锁住,不让其他人操作)和乐观锁(通过给数据加版本号)。

实现步骤

数据库中添加version字段

取出记录时,获取当前version

更新时,version + 1,如果where语句中的version版本不对,则更新失败

具体实现

修改实体类,添加 @Version 注解

@Versionprivate Integer version;

创建MP的配置文件并注册乐观锁到IOC容器中

@Configuration@MapperScan("com.springboot.mybatis_plus.mapper")//可以将主启动类的扫描包配置在这里public class MyBatisPlusConfig {//乐观锁插件,本质为拦截器,加@Version注解@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor();    }}

4) 分页插件

MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能

添加分页插件,配置类中添加@Bean配置

//分页插件,本质为拦截器@Beanpublic PaginationInterceptor paginationInterceptor(){return new PaginationInterceptor();    }

测试

@Testpublic void testSelectPage() {    Page page = new Page<>(1,5);    Page pageParam = userMapper.selectPage(page, null);    pageParam.getRecords().forEach(System.out::println);    System.out.println(pageParam.getCurrent());    System.out.println(pageParam.getPages());    System.out.println(pageParam.getSize());    System.out.println(pageParam.getTotal());    System.out.println(pageParam.hasNext());    System.out.println(pageParam.hasPrevious());}

结果如下:

4065e98b6fc23d2dc4464d07bcc6b250.png

5) 逻辑删除(假删除)

user表添加 deleted字段

ALTER TABLE `user` ADD COLUMN `deleted` boolean DEFAULT false

实体类修改,添加deleted 字段,并加上 @TableLogic 注解

@TableLogicprivate Integer deleted;

application.properties 加入以下配置,此为默认值,如果你的默认值和mp默认的一样,该配置可无

mybatis-plus.global-config.db-config.logic-delete-value=1mybatis-plus.global-config.db-config.logic-not-delete-value=0

测试后发现,数据并没有被删除,deleted字段的值由0变成了1,测试后分析打印的sql语句,是一条update语句

注意:被删除前,数据的deleted 字段的值必须是 0,才能被选取出来执行逻辑删除的操作

6.条件构造器

类图(该图来自尚硅谷Helen老师的讲义)

407a2421f8ffe5144bbcebfa40629937.png

Wrapper :条件构造抽象类,最顶端父类AbstractWrapper :用于查询条件封装,生成 sql 的 where 条件QueryWrapper :查询条件封装UpdateWrapper :Update 条件封装AbstractLambdaWrapper :使用Lambda 语法LambdaQueryWrapper :用于Lambda语法使用的查询WrapperLambdaUpdateWrapper :Lambda 更新封装Wrapper

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值