集成mybatis-plus

1、添加pom.xml

<!--mp逆向工程 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>

2、创建CodeGenerator代码生成类

package com.ds.book.mp;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils; import java.util.ArrayList;
import java.util.List;
import java.util.Scanner; public class CodeGenerator { /**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
} public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator(); // 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("java大师");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc); // 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://175.24.198.63:3306/book?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root@1234!@#");
mpg.setDataSource(dsc); // 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setParent("com.ds.book");
mpg.setPackageInfo(pc); // 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
}; // 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg); // 配置模板
TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController(); templateConfig.setXml(null);
mpg.setTemplate(templateConfig); // 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setTablePrefix("t_");
// strategy.setInclude("t_user");
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
// strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
} }

3、生成crontroller、service、mapper、entity等业务实体类

运行CodeGenerator,生成业务实体类

请输入表名,多个英文逗号分割:

sys_user,sys_menu,sys_role,sys_user_role,sys_role_menu

4、添Mybatis-plus配置类

新增Mybatis-plus配置类,用于配置MyBatis Plus的一些特性。MyBatis Plus是一个MyBatis的增强工具,在Java项目中用来简化开发,提高效率的。下面是对代码的简要说明:

  1. @Configuration:这是一个Spring框架的注解,表示这个类是一个配置类,用于定义和注册beans。

  2. @MapperScan:这个注解告诉Spring去扫描指定包下的MyBatis mapper接口,并将它们注册为Spring beans。

  3. MybatisPlusInterceptor bean:这里创建了一个MyBatis Plus的拦截器,并向其中添加了几个内部拦截器。这些内部拦截器为MyBatis Plus提供了额外的功能。

    • PaginationInnerInterceptor:分页插件,用于在查询时自动添加分页逻辑。
    • BlockAttackInnerInterceptor:防止全表更新和删除插件,用于防止误操作导致整个表的数据被删除或更新。
    • OptimisticLockerInnerInterceptor:乐观锁插件,用于实现乐观锁功能,确保并发操作的数据一致性。
  4. MySqlInjector bean:这是一个自定义的SQL注入器,继承了DefaultSqlInjector。它重写了getMethodList方法,向其中添加了一个InsertBatchSomeColumn方法。这个方法允许你批量插入某些列的数据,而不是插入整行的数据。

    mybatis-plus的顶级IService接口有一个saveBatch()方法,但是它会执行多条insertSql,在数据量大的时候效率会非常差,如果我们是mysql数据库,又不想自己写mapper.xml,mybatis-plus提供了InsertBatchSomeColumn批量insert方法,需要我们自己注入下

这段代码的作用是配置MyBatis Plus的一些高级特性,如分页、防误操作、乐观锁和自定义SQL注入等

@Configuration
@MapperScan({"com.ds.blog.system.mapper","com.ds.blog.admin.mapper"})
public class MybatisPlusConfig { @Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
//添加分页插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//防全表更新删除插件
mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
// 乐观锁插件
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
} @Bean
public MySqlInjector easySqlInjector(){
return new MySqlInjector();
}
}

5、新增批量方法insertBatchSomeColumn

/**
* 使用InsertBatchSomeColumn
*/
class MySqlInjector extends DefaultSqlInjector{
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertBatchSomeColumn());
return methodList;
}
}

定义接口MyBaseMapper,该接口泛型地处理类型T的数据。这个接口扩展(或继承)了另一个接口BaseMapper<T>,意味着它继承了BaseMapper的所有方法,并且可以用于相同类型的数据T

MyBaseMapper接口中,定义了一个新的方法insertBatchSomeColumn,这个方法接受一个类型为T的实体列表(或集合)作为参数。用来批量插入某些列的数据到MySQL数据库中。

总的来说,这个接口在原有的BaseMapper接口基础上增加了一个新的批量插入功能,特别是针对MySQL数据库。通过这样的接口定义,开发者可以在实现类中具体实现这个功能,并在业务逻辑中使用这个批量插入方法,提高数据插入的效率。

public interface MyBaseMapper<T> extends BaseMapper<T> {

    /**
* 批量插入 仅适用于mysql
*
* @param entityList 实体列表
*/
void insertBatchSomeColumn(Collection<T> entityList);
}

6、继承MyBaseMapper

编写业务Mapper,继承MybaseMapper

public interface SysUserMapper extends MyBaseMapper<SysUser> {

    SysUser findByUserName(String username);

    SysUser findByUserId(Long id);

    List<SysUser> findUserList(@Param(Constants.WRAPPER) Wrapper wrapper);
} //实用insertBatchSomeColumn批量插入
sysRoleMenuMapper.insertBatchSomeColumn(sysRoleMenus);

它是这样执行的:

insert into sys_role_menu values (id1,name1,roleId1), (id2,name2,roleId2),(id...,name...,roleId...) ;

springboot集成mybatis-plus的更多相关文章

  1. springboot集成mybatis(二)

    上篇文章<springboot集成mybatis(一)>介绍了SpringBoot集成MyBatis注解版.本文还是使用上篇中的案例,咱们换个姿势来一遍^_^ 二.MyBatis配置版(X ...

  2. springboot集成mybatis(一)

    MyBatis简介 MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyB ...

  3. SpringBoot 集成Mybatis 连接Mysql数据库

    记录SpringBoot 集成Mybatis 连接数据库 防止后面忘记 1.添加Mybatis和Mysql依赖 <dependency> <groupId>org.mybati ...

  4. SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版)

    SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版) ================================ ©Copyright 蕃薯耀 2 ...

  5. SpringBoot集成Mybatis并具有分页功能PageHelper

    SpringBoot集成Mybatis并具有分页功能PageHelper   环境:IDEA编译工具   第一步:生成测试的数据库表和数据   SET FOREIGN_KEY_CHECKS=0;   ...

  6. Springboot集成mybatis(mysql),mail,mongodb,cassandra,scheduler,redis,kafka,shiro,websocket

    https://blog.csdn.net/a123demi/article/details/78234023  : Springboot集成mybatis(mysql),mail,mongodb,c ...

  7. BindingException: Invalid bound statement (not found)问题排查:SpringBoot集成Mybatis重点分析

    重构代码,方法抛出异常:BindingException: Invalid bound statement (not found) 提示信息很明显:mybatis没有提供某方法 先不解释问题原因和排查 ...

  8. SpringBoot集成Mybatis配置动态数据源

    很多人在项目里边都会用到多个数据源,下面记录一次SpringBoot集成Mybatis配置多数据源的过程. pom.xml <?xml version="1.0" encod ...

  9. SpringBoot集成Mybatis实现多表查询的两种方式(基于xml)

     下面将在用户和账户进行一对一查询的基础上进行介绍SpringBoot集成Mybatis实现多表查询的基于xml的两种方式.   首先我们先创建两个数据库表,分别是user用户表和account账户表 ...

  10. SpringBoot集成MyBatis的Bean配置方式

    SpringBoot集成MyBatis的Bean配置方式 SpringBoot是一款轻量级开发的框架,简化了很多原先的xml文件配置方式,接下来就介绍一下如何不适用XML来配置Mybatis spri ...

随机推荐

  1. Python | 函数、数据容器

    1.函数 函数:是组织好的,可重复使用的,用来实现特定功能的代码段. 1.1 简单案例 重复使用计算字符串的长度 str1 = "heystar" str2 = "pyt ...

  2. Redis系列21:缓存与数据库的数据一致性讨论

    Redis系列1:深刻理解高性能Redis的本质 Redis系列2:数据持久化提高可用性 Redis系列3:高可用之主从架构 Redis系列4:高可用之Sentinel(哨兵模式) Redis系列5: ...

  3. uwsgi配置

    编辑nginx配置: server { listen 8098; server_name 127.0.0.1; location / { include uwsgi_params; # uwsgi_p ...

  4. Spring Boot中自动装配机制的原理

    SpringBoot中自动装配机制的原理 1.自动装配,简单来说就是自动把第三方组件的Bean装载到Spring IOC容器里面,不需要开发人员再去写Bean的装配配置, 2.在Spring Boot ...

  5. 「codeforces - 1674F」Madoka and Laziness

    link. 如果做过 codeforces - 1144G 那这题最多 *2200. 序列中的最大值必然为其中一个拐点,不妨设 \(a_p = a_\max\),先讨论另一个拐点 \(i\) 在 \( ...

  6. C++的extern关键字在HotSpot VM中的重要应用

    extern关键字有两个用处: (1)extern在C/C++语言中表示函数和全局变量作用范围(可见性)的关键字,这个关键字会告诉编译器,其声明的函数和变量可以在本模块或其它模块中使用. (2)在C+ ...

  7. MySQL系列之——错误日志(log_error)、二进制日志(binary logs)、慢日志(slow_log)

    文章目录 1.错误日志(log_error) 1.1 作用 1.2 错误日志配置 1.3 日志内容查看 2. binlog(binary logs):二进制日志 ***** 2.1 作用 2.2 bi ...

  8. 2023.09.29 入门级 J2 模拟赛 赛后总结(尝试第一篇总结)

    T1:变换(change) 一道大水题. 赛场上想都没想就切掉了 不难发现,转换的过程只和a 和b 的二进制位有关,且不同二进制位之间无关.我们可以将a 和b 转化为二进制表示,每一位分别判断,如果这 ...

  9. SQLPLUS使用及Oracle表空间设定自动扩展

    起因:ERP不能登陆,Oracle无法访问,报错如下 后联系鼎捷se提供以下解决方案: 该问题是由于Oracle审计表AUD$数据过大导致数据库异常,现已登录DB服务器使用oracle账号执行语句tr ...

  10. 今天的第二道tarjan:受欢迎的牛

    原题来自:USACO 2003 Fall 题目描述 每头奶牛都梦想成为牛棚里的明星.被所有奶牛喜欢的奶牛就是一头明星奶牛.所有奶牛都是自恋狂,每头奶牛总是喜欢自己的.奶牛之间的"喜欢&quo ...