发布于2026-07-05 阅读(0)
扫一扫,手机访问
说起 Ja va 后端开发中的 ORM 工具,MyBatis-Plus 近几年几乎成了很多项目的标配。它的优势在于把单表 CRUD 做成了开箱即用的“懒人包”,省去了大量重复的 XML 编写工作。今天我们不谈虚的,直接上手搭一个 Spring Boot + MyBatis-Plus 的完整项目,涵盖了从项目初始化到分页查询的整个流程。

这一步最简单——用 Spring Initializr 或者你惯用的 IDE 直接创建一个 Spring Boot 项目。记得勾选下面几个模块:
项目骨架搭好后,在 pom.xml 里加上 MyBatis-Plus 的 starter。目前最新的稳定版是 3.5.5:
com.baomidou mybatis-plus-boot-starter 3.5.5
在 application.yml 中配置数据库连接信息,顺便把 MyBatis-Plus 的 SQL 日志打印打开,方便调试:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印SQL日志
建一张 user 表,然后写实体类。用 @TableName 指定表名,@TableId 指定主键策略:
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
这才是体现 MyBatis-Plus 便捷性的地方——写一个接口继承 BaseMapper,什么 SQL 都不用写,基本的增删改查就已经内置了:
@Mapper public interface UserMapper extends BaseMapper{ // BaseMapper 已经提供了CRUD方法,不需要写SQL }
写几个简单的测试用例,跑一下看看效果。通常我们习惯在 Spring Boot 的测试模块里操作:
@SpringBootTest
class UserMapperTests {
@Autowired
private UserMapper userMapper;
@Test
void testSelect() {
List users = userMapper.selectList(null);
System.out.println(users);
}
@Test
void testInsert() {
User user = new User();
user.setName("张三");
user.setAge(20);
user.setEmail("zhangsan@example.com");
int rows = userMapper.insert(user);
System.out.println("插入成功:" + rows);
}
}
运行 testSelect,控制台会打印出数据库中的所有用户数据;testInsert 则会验证插入是否正常。这一步走通了,后面的操作就顺理成章了。
除了最简单的全表查询,日常开发中更常用的是带条件查询、分页、更新和删除。下面列举几个典型场景:
// 根据ID查询 User user = userMapper.selectById(1L); // 条件查询:用 LambdaQueryWrapper 构造条件,既安全又直观 Listusers = userMapper.selectList( new LambdaQueryWrapper () .eq(User::getAge, 20) .like(User::getName, "张") ); // 分页查询(需要先配置分页插件,见下一节) Page page = userMapper.selectPage( new Page<>(1, 10), null ); // 更新:直接传入有主键的实体即可 userMapper.updateById(user); // 删除 userMapper.deleteById(1L);
可以看到,除了表结构变化时需要调整实体类,几乎不会再碰 XML 文件。尤其是 LambdaQueryWrapper,避免了硬编码字段名,重构时非常省心。
如果项目里要用分页,需要单独注册一个 MyBatis-Plus 的拦截器。很简单,加个配置类就行:
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
配置好之后,前面的分页查询就能正常工作了。实际上 MyBatis-Plus 还提供了许多其他实用的拦截器,比如乐观锁插件、防止全表更新插件等,不过那是进阶话题了。
回头来看,MyBatis-Plus 最核心的价值就是单表操作不用写 SQL。BaseMapper 帮你封装了几乎所有常用的增删改查,日常开发中至少能省掉 70% 的重复代码。如果你还在手工写大量的 insert 和 selectById 的 XML,确实值得给项目换上这个工具,体验一下“开箱即用”的爽快感。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8