目录
一、使用 MybatisPlus 基本步骤
1. 引入 MybatisPlus 依赖
2. 定义Mapper接口并继承BaseMapper
二、MybatisPlus 常用配置
三、自定义SQL
四、IService 接口
1. 批量新增的效率问题
2. 配置方式
五、插件功能
1. 分页插件
一、使用 MybatisPlus 基本步骤
1. 引入 MybatisPlus 依赖
<!--MybatisPlus-->
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version>
</dependency>
2. 定义Mapper接口并继承BaseMapper
public interface UserMapper extends BaseMapper<User> {
}
二、MybatisPlus 常用配置
MyBatisPlus的配置项继承了MyBatis原生配置和一些自己特有的配置。例如:
mybatis-plus:type-aliases-package: com.itheima.mp.domain.po # 别名扫描包mapper-locations: "classpath*:/mapper/**/*.xml" # Mapper.xml文件地址,默认值configuration:map-underscore-to-camel-case: true # 是否开启下划线和驼峰的映射cache-enabled: false # 是否开启二级缓存,默认为falseglobal-config:db-config:id-type: assign_id # id为雪花算法生成,默认值update-strategy: not_null # 更新策略:只更新非空字段
三、自定义SQL
我们可以利用MyBatisPlus的Wrapper来构建复杂的Where条件,然后自己定义SQL语句中剩下的部分。
四、IService 接口
1. 批量新增的效率问题
在使用 MybatisPlus 批处理方法进行新增、更新、删除操作时。Mysql 驱动可能默认不会优化这些批量语句。也就是说,即使调用了批处理方法,驱动可能还是会将每个SQL单独发送到数据库执行,这样效率不高。比如,插入100条数据,可能需要发送100次插入语句,网络开销大。
可以考虑开启 rewriteBatchedStatements 参数,开启此参数后,JDBC 驱动会将多个独立的 SQL 语句合并为单个高效语句。例如,批量插入 INSERT INTO table (col) VALUES (?)
会被重写为 INSERT INTO table (col) VALUES (?), (?), ...
,显著减少网络传输和数据库解析开销。
2. 配置方式
在 JDBC 连接 URL 中添加参数:
jdbc:mysql://localhost:3306/db?rewriteBatchedStatements=true
在mysql 的官方文档中,rewriteBatchedStatements 的默认值是 false
五、插件功能
1. 分页插件
如果使用 MybatisPlus 自带的分页插件,就不用使用其他插件了,比如PageHelper
首先,要在配置类中注册MyBatisPlus的核心插件,同时添加分页插件:
@Configuration
public class MybatisConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {// 1.初始化核心插件MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 2.添加分页插件PaginationInnerInterceptor pageInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);pageInterceptor.setMaxLimit(1000L); // 设置分页上限interceptor.addInnerInterceptor(pageInterceptor);return interceptor;}
}