MyBatis-Plus学习
admin
2024-03-31 07:43:15
0

MyBatis-Plus

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

特征

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

一、快速开始

maven依赖

com.baomidoumybatis-plus-boot-starter-test3.5.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)
);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');

配置application.properties文件

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.name=defaultDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

编写pojo类User

package com.rui.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {private Long id;private String name;private Integer age;private String email;
}

编写mapper类

package com.rui.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rui.pojo.User;
import org.springframework.stereotype.Repository;//在对应的Mapper上面实现基本的类BaseMapper
@Repository
public interface UserMapper extends BaseMapper {//所有的CRUD已经编写完成
}

在springboot启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

@MapperScan("com.rui.mapper")

启动测试!

二、CRUD等拓展

插入操作

@Test
void test1() {User user = new User();user.setName("叶辰");user.setAge(18);user.setEmail("206875469@qq.com");System.out.println(userMapper.insert(user));
}

主键生成策略

默认 ID_WORKER 全局唯一id

分布式系统唯一id生成:https://www.cnblogs.com/haoxinyue/p/5208136.html

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

设置主键自增:在数据库表中设置id自动递增,在User类中id属性上面添加@TableId(type = IdType.AUTO

其与的源码解释

public enum IdType {AUTO(0), // 数据库id自增NONE(1), // 未设置主键INPUT(2), // 手动输入ID_WORKER(3), // 默认的全局唯一idUUID(4), // 全局唯一id uuidID_WORKER_STR(5); //ID_WORKER 字符串表示法
}

更新操作

使用updateById()参数是泛型T

@Test
void test2() {User user = new User();user.setId(3L);user.setName("叶辰");System.out.println(userMapper.updateById(user));
}

所有的sql都是帮你自动动态的配置的!

自动填充

  • 数据库级别

  • 代码级别

添加字段

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

创建MyMetaObjectHandler实现MetaObjectHandler接口

package com.rui.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;import java.util.Date;@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {log.info("插入自动填充开始...");//default MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)this.setFieldValByName("createTime",new Date(),metaObject);this.setFieldValByName("updateTime",new Date(),metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {log.info("更新自动填充开始...");this.setFieldValByName("updateTime",new Date(),metaObject);}
}

测试

乐观锁、悲观锁

乐观锁 : 故名思意十分乐观,它总是认为不会出现问题,无论干什么不去上锁!如果出现了问题, 再次更新值测试

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

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

乐观锁实现方式:

  • 取出记录时,获取当前 version
  • 更新时,带上这个 version
  • 执行更新时, set version = newVersion 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

乐观锁插件

数据库和实体类添加int version

@Version
private Integer version;

创建MyBatisPlusConfig配置类

package com.rui.config;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;@MapperScan("com.rui.mapper")
@EnableTransactionManagement
@Configuration
public class MyBatisPlusConfig {//注册乐观锁插件//旧版// @Bean// public OptimisticLockerInterceptor optimisticLockerInterceptor() {//     return new OptimisticLockerInterceptor();// }//新版@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return mybatisPlusInterceptor;}}

测试

//测试乐观锁成功
@Test
void test3() {User user = userMapper.selectById(1L);user.setName("root");user.setEmail("root");userMapper.updateById(user);
}
//测试乐观锁失败
@Test
void test4() {//线程1User user = userMapper.selectById(1L);user.setName("root111");user.setEmail("root111");//线程2:模拟插队操作User user2 = userMapper.selectById(1L);user2.setName("root222");user2.setEmail("root222");userMapper.updateById(user2);//自旋锁来多次尝试提交userMapper.updateById(user);//如果没有乐观锁数据库中就会覆盖插队线程2的值!
}

查询操作

@Test
void test5() {//单个查询System.out.println("单个查询------");System.out.println(userMapper.selectById(1));//批量查询System.out.println("批量查询------");for (User selectBatchId : userMapper.selectBatchIds(Arrays.asList(1, 2, 3))) {System.out.println(selectBatchId);}//条件查询mapSystem.out.println("条件查询map------");HashMap map = new HashMap<>();map.put("name","叶辰");System.out.println(userMapper.selectByMap(map));//全部查询System.out.println("全部查询------");//参数是一个wapper,条件构造器for (User user : userMapper.selectList(null)) {System.out.println(user);}
}

分页查询

修改MyBatisPlusConfig类

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();//乐观锁插件mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//分页插件mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//也可以不传DbType.MYSQL,为空时会通过URL判断数据库类型// if (url.contains(":mysql:") || url.contains(":cobar:")) {//              return DbType.MYSQL;return mybatisPlusInterceptor;
}

测试

@Test
void test6() {Page page = new Page<>(2, 5);userMapper.selectPage(page,null);page.getRecords().forEach(System.out::println);
}

删除操作

与select类似

 @Test
void test7() {userMapper.deleteById(1582728670388129794L);userMapper.deleteBatchIds(Arrays.asList(1,2,3));HashMap map = new HashMap<>();map.put("name","叶辰");userMapper.deleteByMap(map);
}

逻辑删除

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

逻辑删除 :再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1

管理员可以查看删除的记录!防止数据的丢失!

在数据表和实体类中添加deleted字段

@TableLogic //逻辑删除
private Integer deleted;

高版本已经不用再去配置MyBatisPlusConfig插入组件

只需要注解+application.properties配置即可

#逻辑删除
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

查询会自动加上delete字段,除了管理员之外无法查询

执行SQL分析打印

导入依赖

p6spyp6spy3.9.1

修改driver-class-name url application.properties文件

spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.name=defaultDataSource
spring.datasource.url= jdbc:p6spy:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

spy.properties文件

modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

测试使用!上线会影响性能

条件构造器

  • AbstractWrapper
    allEq、eq、ne、gt、ge、lt、le、between、notBetween、
    like、notLike、likeLeft、likeRight、isNull、isNotNull、in、
    notIn、inSql、notInSql、groupBy、orderByAsc、orderByDesc、orderBy、
    having、func、or、and、nested、apply、last、exists、notExists
  • QueryWrapper
    select
  • UpdateWrapper

​ set、setSql、lambda

测试等等

package com.rui.mybatis_plus;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rui.mapper.UserMapper;
import com.rui.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class WrapperTest {//继承了BaseMapper,所有的方法都来自自己的父类@Autowiredprivate UserMapper userMapper;@Testvoid test1(){//查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于20QueryWrapper wrapper = new QueryWrapper<>();wrapper.isNotNull("name").isNotNull("email").ge("age",20);userMapper.selectList(wrapper).forEach(System.out::println);}@Testvoid test2(){//查询指定nameQueryWrapper wrapper = new QueryWrapper<>();wrapper.eq("name","叶辰");userMapper.selectList(wrapper).forEach(System.out::println);}@Testvoid test3(){//查询指定nameQueryWrapper wrapper = new QueryWrapper<>();wrapper.between("age",12,20);userMapper.selectList(wrapper).forEach(System.out::println);System.out.println("数量为:"+userMapper.selectCount(wrapper));}@Testvoid test4(){//模糊查询QueryWrapper wrapper = new QueryWrapper<>();wrapper.notLike("name","叶").likeRight("email","t");userMapper.selectList(wrapper).forEach(System.out::println);}@Testvoid test5(){//模糊查询QueryWrapper wrapper = new QueryWrapper<>();wrapper.inSql("id","select id from user where id<5");userMapper.selectList(wrapper).forEach(System.out::println);}}

代码自动生成器

3.5.1以下的版本:

dao、pojo、service、controller都给我自己去编写完成!

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、 Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

package com.kuang;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
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;
// 代码自动生成器
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");gc.setAuthor("狂神说");gc.setOpen(false);gc.setFileOverride(false); // 是否覆盖gc.setServiceName("%sService"); // 去Service的I前缀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/kuang_community?useSSL=false&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("blog");pc.setParent("com.kuang");pc.setEntity("entity");pc.setMapper("mapper");pc.setService("service");pc.setController("controller");mpg.setPackageInfo(pc);//4、策略配置StrategyConfig strategy = new StrategyConfig();strategy.setInclude("blog_tags","course","links","sys_settings","user_record","user_say"); // 设置要映射的表名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 tableFills = new ArrayList<>();tableFills.add(gmtCreate);tableFills.add(gmtModified);strategy.setTableFillList(tableFills);// 乐观锁strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2mpg.setStrategy(strategy);mpg.execute(); //执行}
}

测试生成

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rx4dGf0S-1666696695905)(D:\program files\TyporaImg\image-20221021155036126.png)]

3.5.1以上的版本:`

com.baomidoumybatis-plus-generator最新版本

快速生成

FastAutoGenerator.create("url", "username", "password").globalConfig(builder -> {builder.author("baomidou") // 设置作者.enableSwagger() // 开启 swagger 模式.fileOverride() // 覆盖已生成文件.outputDir("D://"); // 指定输出目录}).packageConfig(builder -> {builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名.moduleName("system") // 设置父包模块名.pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径}).strategyConfig(builder -> {builder.addInclude("t_simple") // 设置需要生成的表名.addTablePrefix("t_", "c_"); // 设置过滤表前缀}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板.execute();

交互式生成

FastAutoGenerator.create(DATA_SOURCE_CONFIG)// 全局配置.globalConfig((scanner, builder) -> builder.author(scanner.apply("请输入作者名称?")).fileOverride())// 包配置.packageConfig((scanner, builder) -> builder.parent(scanner.apply("请输入包名?")))// 策略配置.strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all"))).controllerBuilder().enableRestStyle().enableHyphenStyle().entityBuilder().enableLombok().addTableFills(new Column("create_time", FieldFill.INSERT)).build())/*模板引擎配置,默认 Velocity 可选模板引擎 Beetl 或 Freemarker.templateEngine(new BeetlTemplateEngine()).templateEngine(new FreemarkerTemplateEngine())*/.execute();// 处理 all 情况
protected static List getTables(String tables) {return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}

样例

相关内容

热门资讯

上节育环后需要注意什么 一、休息与活动 上节育环后要适当休息,避免剧烈运动和重体力劳动,一般建议休息1 - 2天。因为过早进...
挖矿收益不足3美分!比特币暴跌... 来源:环球市场播报 TMG Core 展台的液体浸没式冷却矿槽中的加密货币矿机。 罗森布拉特证券公...
众机构唱多三星电子:存储巨头冲... 财联社2月25日讯(编辑 史正丞)随着三星电子周二收涨3.6%,迈上每股20万韩元的历史新高,分析师...
增值税发票数据显示:春节假期消... 新华社北京2月24日电(记者刘开雄)记者2月24日从国家税务总局获悉,增值税发票数据显示,2026年...
从“向外求索”到“向内安顿”的... 从“向外求索”到“向内安顿”的消费觉醒 当商务宴席上的茅台与书房中静静摆放的谦夫子养生露酒同时出现在...
千寻智能完成近20亿元融资 北京商报讯(记者 陶凤 王天逸)2月24日,具身智能头部企业千寻智能宣布,近日连续完成两轮融资,金额...
原创 银... 最近不少人发现,家附近的银行网点悄悄关门了,有的贴出公告终止营业,有的直接撤柜清空,就连工商银行、建...
美联储理事库克称央行可能无法应... 来源:环球市场播报 美联储理事丽莎·库克警告称,美国央行可能无法应对因采用人工智能而导致的失业率上升...
焦点访谈|这个春节假期,消费市... 来源:滚动播报 (来源:千龙网) 金马昂首,新春纳福。刚刚过去的丙午年春节假期,消费市场购销两旺持续...
亚朵节后价格“跳水”超70% 春节过后,部分热门小城的亚朵酒店房价上演“过山车”行情,房价节前飙升,节后迅速跳水,巨大的价格波动引...
原创 金... 你绝对想不到,同样一克999足金,在深圳水贝批发市场只要1334元,走进周大福门店却变成1545元,...
德兰明海冲击港交所!递表前大手... 又一家储能企业“叩响”了港交所大门。近期,港交所官网显示,中小型用户侧储能企业深圳市德兰明海新能源股...
绿茶集团、猫眼娱乐发布正面盈利... |2026年2月25日 星期三| NO.1绿茶集团发布正面盈利预告 2月24日港股收市后,绿茶集团(...
安宁市的历史文化及名人有哪些 安宁市,这座坐落在彩云之南的城市,宛如一颗璀璨明珠,散发着迷人的历史文化魅力。在这里,岁月留下了深深...
中国央行连续12个月加量续作M... 来源:中国新闻网 中新社北京2月24日电 (陶思阅)中国央行24日发布中期借贷便利(MLF)招标公告...
不是15%?特朗普10%全球关... 据美国海关及边境保卫局(CBP)发布消息,特朗普政府将实施的新全球关税为10%。 第一财经收到的CB...
2026年春节出游人次、消费金... 2026年春节,为期9天的超长假期点燃了全国消费热情,多项核心数据创下历史纪录。 经文化和旅游部数据...
美国联邦存款保险公司(FDIC... 美国联邦存款保险公司(FDIC):美国银行业存款季环比下滑2%。
2026春节AI大战深度复盘:... 主编温静导读:2026年春节,元宝、千问、豆包三大巨头以红包、免单为杠杆,发动了一场规模空前的用户争...