4.1 介绍
MyBatis-Plus(简称 MP)是一个基于 MyBatis 的增强工具,提供通用 CRUD 操作、代码生成器、条件构造器、分页插件等功能,简化开发流程,提升效率。
4.2 特点
-
无侵入:只做增强不做修改,与 MyBatis 完全兼容。
-
CRUD 简化:内置通用 Mapper 和 Service,减少 SQL 编写。
-
代码生成器:自动生成 Entity、Mapper、Service、Controller 代码。
-
条件构造器:通过
QueryWrapper
或LambdaQueryWrapper
动态构建查询条件。 -
分页插件:支持物理分页,自动优化 COUNT 语句。
4.3 如何使用
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-spring-boot3-starter</artifactId><version>3.5.10.1</version> </dependency>
在 application.yml
配置文件中添加 H2 数据库的相关配置:
# DataSource Config spring:datasource:driver-class-name: org.h2.Driverusername: rootpassword: 123456sql:init:schema-locations: classpath:db/schema-h2.sqldata-locations: classpath:db/data-h2.sql
在 Spring Boot 启动类中添加 @MapperScan
注解,扫描 Mapper 文件夹:
@SpringBootApplication @MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper") public class Application { public static void main(String[] args) {SpringApplication.run(Application.class, args);} }
编码
编写实体类 User.java:
@Data @TableName("`user`") public class User {private Long id;private String name;private Integer age;private String email; }
编写 Mapper 接口类 UserMapper.java
:
public interface UserMapper extends BaseMapper<User> { }
5. mp-增加
// 插入单条记录 User user = new User(); user.setName("张三"); user.setAge(25); userMapper.insert(user); // 批量插入 List<User> userList = Arrays.asList(new User("李四", 30), new User("王五", 28)); userMapper.insertBatchSomeColumn(userList);
6. mp-删除
// 根据 ID 删除 userMapper.deleteById(1L); // 根据条件删除(删除年龄大于 30 的用户) QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.gt("age", 30); userMapper.delete(wrapper);
7. mp-修改
// 根据 ID 更新 User user = userMapper.selectById(2L); user.setName("赵六"); userMapper.updateById(user); // 条件更新(将年龄小于 20 的用户设为无效) UpdateWrapper<User> wrapper = new UpdateWrapper<>(); wrapper.lt("age", 20).set("status", 0); userMapper.update(null, wrapper);
8. mp-查询
8.1 根据主键查询---省略
User user = userMapper.selectById(1L);
8.2 根据各种条件查询
// 查询年龄在 20-30 之间的用户 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.between("age", 20, 30); List<User> users = userMapper.selectList(wrapper); // 使用 Lambda 表达式(查询名字包含 "张" 的用户) LambdaQueryWrapper<User> lambdaWrapper = new LambdaQueryWrapper<>(); lambdaWrapper.like(User::getName, "张"); List<User> users = userMapper.selectList(lambdaWrapper);
8.3 根据条件查询一条记录
QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name", "刘德华"); User user = userMapper.selectOne(wrapper);
8.4 分页查询
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-jsqlparser</artifactId><version>3.5.10.1</version> <!-- 确保版本和 MyBatis Plus 主包一致 --> </dependency>
属性名 | 类型 | 默认值 | 描述 |
---|---|---|---|
overflow | boolean | false | 溢出总页数后是否进行处理 |
maxLimit | Long | 单页分页条数限制 | |
dbType | DbType | 数据库类型 | |
dialect | IDialect | 方言实现类 |
配置类
@Configuration @MapperScan("scan.your.mapper.package") public class MybatisPlusConfig { /*** 添加分页插件*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加// 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbTypereturn interceptor;} }
Page<User> page = new Page<>(1, 10); // 第 1 页,每页 10 条 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.orderByDesc("create_time"); IPage<User> userPage = userMapper.selectPage(page, wrapper); System.out.println("总页数:" + userPage.getPages()); System.out.println("总记录数:" + userPage.getTotal());
8.5 联表查询也使用mp的分页。
/*** 联表查询 使用mp的分页功能。*/@Testpublic void testLianbiao(){// @Param("ew") Wrapper<T> queryWrapperPage<User> page=new Page<>(1,3);QueryWrapper<User> wrapper=new QueryWrapper<>();wrapper.eq("name","刘德华");IPage<User> users=userMapper.selectUserWithDept(page,wrapper);System.out.println("总页码:"+page.getPages());System.out.println("总条数:"+page.getTotal());System.out.println("当前页记录:"+page.getRecords());}
<resultMap id="baseMaper" type="com.ykq.entity.User" autoMapping="true"><id property="id" column="id"/><association property="dept" javaType="com.ykq.entity.Dept" autoMapping="true"><id column="did" property="did"/></association></resultMap><select id="selectUserWithDept" resultMap="baseMaper">select * from user u join tbl_dept d on u.did=d.did where isdeleted=0 <if test="ew!=null">and ${ew.sqlSegment}</if> </select>
注意事项:
-
联表查询需自定义 SQL,MP 分页插件会自动处理分页逻辑。
-
使用
QueryWrapper
时,条件字段名需与数据库列名一致。 -
分页参数
Page
的current
和size
需明确指定。