MyBatis-Plus极速开发指南
MyBatis-Plus简介
MyBatis-Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,简化开发,提高效率。它提供了以下主要特性:
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,少量配置即可实现大部分 CRUD 操作
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件
- 支持主键自动生成:支持多达 4 种主键策略
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作
项目搭建
创建 SpringBoot 项目
在 pom.xml 中添加必要依赖:
org.springframework.boot spring-boot-starter com.baomidou mybatis-plus-boot-starter 3.5.1 org.projectlombok lombok true mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test
配置数据源
在 application.yml 中配置数据库连接:
server: port: 8080spring: datasource: url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false driver-class-name: com.mysql.cj.jdbc.Driver type: com.zaxxer.hikari.HikariDataSource username: root password: 123456
核心功能演示
实体类定义
使用 Lombok 简化代码:
@Datapublic class User { private Integer id; private String name; private Integer age; private String email; public User() {} public User(Integer id, String name, Integer age, String email) { this.id = id; this.name = name; this.age = age; this.email = email; }}
Mapper 接口
只需继承 BaseMapper 即可获得丰富的 CRUD 方法:
@Repositorypublic interface UserMapper extends BaseMapper { // 无需编写任何方法,即可获得完整CRUD功能}
基础 CRUD 操作
@SpringBootTestpublic class MyBatisplusTest extends AbstractTestNGSpringContextTests { @Autowired private UserMapper userMapper; // 查询所有用户 @Test public void testSelectList() { userMapper.selectList(null).forEach(System.out::println); } // 插入用户 @Test public void testInsert() { User user = new User(null, \"张三\", 23, \"zhangsan@qcby.com\"); int result = userMapper.insert(user); System.out.println(\"受影响行数:\" + result); System.out.println(\"id自动获取:\" + user.getId()); }}
MyBatis-Plus 特性详解
主键生成策略
MyBatis-Plus 支持多种主键生成策略:
- AUTO:数据库 ID 自增
- NONE:无状态,该类型为未设置主键类型
- INPUT:用户输入 ID
- ASSIGN_ID:分配 ID
- ASSIGN_UUID:分配 UUID
条件构造器
MyBatis-Plus 提供了强大的条件构造器 QueryWrapper 和LambdaQueryWrapper:
// 使用QueryWrapperQueryWrapper queryWrapper = new QueryWrapper();queryWrapper.like(\"name\", \"张\").lt(\"age\", 30);List users = userMapper.selectList(queryWrapper);// 使用LambdaQueryWrapper(推荐)LambdaQueryWrapper lambdaQuery = Wrappers.lambdaQuery();lambdaQuery.like(User::getName, \"张\").lt(User::getAge, 30);List users = userMapper.selectList(lambdaQuery);
分页功能
添加分页插件配置
@Configurationpublic class MyBatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; }}
使用分页查询
@Testpublic void testPage() { Page page = new Page(1, 5); // 当前页,每页大小 IPage userPage = userMapper.selectPage(page, null); System.out.println(\"总页数:\" + userPage.getPages()); System.out.println(\"总记录数:\" + userPage.getTotal()); userPage.getRecords().forEach(System.out::println);}