MyBatisPlus

本文详细介绍了MyBatisPlus的使用,包括添加依赖、启动类配置、数据库连接配置、BatisPlusConfig配置类、自动填充策略、主键生成策略、乐观锁、分页查询、逻辑删除以及性能分析插件的使用。同时,提供了代码自动生成器的示例,帮助开发者快速生成代码。此外,还展示了条件构造器的多种查询方法,便于日常开发中进行灵活的数据查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官网:https://mp.baomidou.com/

自定义模板的MyBatisPlus https://blog.youkuaiyun.com/qq_45246098/article/details/123023742

一、MyBatisPlus介绍

MyBatis Plus,简化 MyBatis !为简化开发而生

二、MyBatisPlus使用

2.1 添加依赖

  • swagger2
  • lombok
  • MyBatisPlus里面集成了MyBatis 所以不用再加MyBatis依赖 否则容易报错
<!-- swagger2 --> 
<dependency>
 <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- swagger-ui --> 
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- mybatis-plus --> 
<dependency> 
	<groupId>com.baomidou</groupId> 
	<artifactId>mybatis-plus-boot-starter</artifactId> 
	<version>3.2.0</version> 
</dependency>
<dependency>
   <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.2.0</version>
</dependency>
<!-- mybatis-plus 模板 --> 
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>

2.2 启动类添加注解

@MapperScan(“com.xu.mapper”)

2.3 application.properties

# 设置开发环境(使用性能分析插件要求为开发或测试环境)
spring.profiles.active=dev
# 端口号
spring.port-=9090

# 数据库连接配置
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# 配置日志 控制台输出sql语句
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

2.4 添加BatisPlusConfig配置类

@MapperScan("com.xujiu.mapper")  // 扫描我们的 mapper 文件夹
@EnableTransactionManagement      // 启动事务管理(乐观锁)
@Configuration									 // 配置类
public class MyBatisPlusConfig {

    // 注册乐观锁插件
    //对应version属性添加注解@Version
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

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

    // 逻辑删除组件
    //实体类中属性添加注解@TableLogic
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }
    
    //SQL执行效率插件
    @Bean
    @Profile({"dev","test"})// 设置 dev test 环境开启,保证我们的效率
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(100); // 设置sql执行的最大时间,如果超过了则不执行
        performanceInterceptor.setFormat(true); //是否开启代码格式化(更好读sql语句)
        return performanceInterceptor;
    }
}

2.5 添加MyMetaObjectHandler自动填充`配置类

代码级别的自动填充策略
在执行插入和修改操作时自动完成create_time update_time填充
删除字段的默认值及自动更新 数据类型设置为 datetime

  • 实体类字段属性上需要增加注解
@TableField(fill = FieldFill.INSERT) 
private Date createTime; 
@TableField(fill = FieldFill.INSERT_UPDATE) 
private Date updateTime;
  • 添加配置类
@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中!
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);
    }
}

2.6 代码自动生成器

  • 新建一个AutoCode 类
  • 策略配置 中修改想要生成的表名
  • 修改带()的内容后执行此类即可
// 代码自动生成器 
public class AutoCode {

 public static void main(String[] args) {
        // 代码生成器
        //导入com.baomidou.mybatisplus.generator.AutoGenerator;
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String oPath = System.getProperty("user.dir");//得到当前项目的路径
        gc.setOutputDir(oPath + "/src/main/java");   //生成文件输出根目录
        //(修改作者名)
        gc.setAuthor("许久龙");  // 作者
        gc.setOpen(false);  // 生成代码后是否打开文件
        gc.setFileOverride(true);// 是否覆盖原文件
        //gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE); //注释的日期格式只显示时间
        gc.setMapperName("%sMapper");//去掉生成的Mapper文件前缀
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        // 数据源配置(修改对应数据源)
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/company_frame?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置(可修改)
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.system");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名及地址 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return oPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);//开启实体类Lombok注解
        strategy.setRestControllerStyle(true);//生成Rest风格controller
        strategy.setEntityTableFieldAnnotationEnable(true); //生成@TableField
        //(修改要生成的表名)
        strategy.setInclude(new String[]{
                "sys_dept", "sys_file", "sys_log", "sys_permission",
                "sys_role", "sys_role_permission", "sys_user_role",
                "sys_user", "sys_rotation_chart"
        });// 需要生成的表

		// 自动填充配置
		//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.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("sys_"); //去掉表前缀
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

三、主键生成策略

id生成策略 默认为ID_WORKER 全局唯一id(雪花算法生成的)

AUTO // id自增 数据库id字段必须设置为int自增
NONE // 未设置主键
INPUT // 手动输入 insert操作是不设置id值则为null
ID_WORKER // 默认的全局唯一id 雪花算法
UUID// 全局唯一id uuid
ID_WORKER_STR //ID_WORKER 字符串表示法

  • 在id属性上添加注解@TableId(type = IdType.AUTO)
  // 对应数据库中的主键 (uuid、自增id、雪花算法、redis、zookeeper!)
    @TableId(type = IdType.AUTO)
    private Long id;
  • 数据库表id字段开启自增

四、自动填充策略(具体看上面2.3)

在执行插入和修改操作时自动完成create_time update_time填充

  • 删除数据库创建时间、修改时间字段的默认值
  • 实体类字段属性上需要增加注解
  • 添加配置类

五、乐观锁

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

  • 乐观锁实现方式:
    取出记录时,获取当前 version
    更新时,带上这个 version
    执行更新时, set version = newVersion where version = oldVersion
    如果 version 不对,就更新失败

  • 给数据库中增加version字段!设置默认值为1

  • 实体类加对应的字段并加注解@Version

@Version 
private Integer version;
  • 配置类里添加乐观锁组件

六、分页查询

  • 配置类里添加分页组件
  • 使用
// 测试分页查询 
@Test 
public void testPage(){ 
	// 参数一:当前页 
	// 参数二:页面大小 
	Page<User> page = new Page<>(2,5); 
	userMapper.selectPage(page,null); 
	page.getRecords().forEach(System.out::println);
	//计算总数据数 
	System.out.println(page.getTotal()); 
}

七、逻辑删除

物理删除 :从数据库中直接移除
逻辑删除 :在数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1
(配置后实际执行的是修改操作)

  • 数据库表中添加字段deleted 设置默认值为0 (0 正常 1 删除)
  • 实体类中增加属性并添加注解@TableLogic
@TableLogic //逻辑删除 
private Integer deleted;
  • 配置类里添加逻辑删除组件
  • yml/propertied文件添加配置
mybatis-plus.global-config.db-config.logic-delete-value=1 
mybatis-plus.global-config.db-config.logic-not-delete-value=0

在这里插入图片描述
在这里插入图片描述

八、性能分析插件

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

  • 配置类里添加性能分析组件
  • 在SpringBoot中配置环境为dev或者 test 环境
    在这里插入图片描述

九、条件构造器

官网API https://baomidou.com/pages/10c804/#abstractwrapper

@Test 
void contextLoads() { 
	// 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12 
	QueryWrapper<User> wrapper = new QueryWrapper<>(); 
	wrapper 
		.isNotNull("name") 
		.isNotNull("email") 
		.ge("age",12); 
	userMapper.selectList(wrapper).forEach(System.out::println); 
} 
@Test 
void test2(){ 
	// 查询名字狂神说 
	QueryWrapper<User> wrapper = new QueryWrapper<>(); 
	wrapper.eq("name","狂神说"); 
	User user = userMapper.selectOne(wrapper); // 查询一个数据,出现多个结果使用List或者 Map 
	System.out.println(user); 
} 
@Test 
void test3(){ 
	// 查询年龄在 20 ~ 30 岁之间的用户 
	QueryWrapper<User> wrapper = new QueryWrapper<>(); 
	wrapper.between("age",20,30); // 区间 
	Integer count = userMapper.selectCount(wrapper);// 查询结果数 
	System.out.println(count); 
} 
// 模糊查询 notLike likeRight
@Test 
void test4(){ 
	// 查询年龄在 20 ~ 30 岁之间的用户 
	QueryWrapper<User> wrapper = new QueryWrapper<>(); 
	// 左和右 t% 
	wrapper 
		.notLike("name","e") 
		.likeRight("email","t"); 
	List<Map<String, Object>> maps = userMapper.selectMaps(wrapper); 
	maps.forEach(System.out::println); 
} 
// 模糊查询 inSql
@Test 
void test5(){ 
	QueryWrapper<User> wrapper = new QueryWrapper<>(); 
	// id 在子查询中查出来 
	wrapper.inSql("id","select id from user where id<3"); 
	List<Object> objects = userMapper.selectObjs(wrapper); 
	objects.forEach(System.out::println); 
}
// 排序 orderByAsc
@Test 
void test6(){ 
	QueryWrapper<User> wrapper = new QueryWrapper<>(); 
	// 通过id进行排序 
	wrapper.orderByAsc("id"); 
	List<User> users = userMapper.selectList(wrapper); 
	users.forEach(System.out::println); 
}

//查询指定字段 select
@Test
public void selectByWrapper10() {
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();
     queryWrapper.select("name", "age").like("name", "雨");
     List<User> users = userMapper.selectList(queryWrapper);
     users.forEach(System.out::println);
}
//查询除指定字段的其他字段 select
@Test
public void selectByWrapper11() {
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();
     queryWrapper.select(User.class, info -> !info.getColumn().equals("manager_id")
             && !info.getColumn().equals("create_time"));
     List<User> users = userMapper.selectList(queryWrapper);
     users.forEach(System.out::println);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值