MyBatis-Plus 入门:BaseMapper 与 Service 封装
MyBatis-Plus(简称 MP)是 MyBatis 的增强工具,"只做增强不做改变",不侵入原有 MyBatis 代码,却把单表 CRUD 从"写 SQL"变成"调方法"。本节讲依赖配置、BaseMapper 与 Service 三层封装。
依赖与配置
Spring Boot 项目引入 starter(版本以官方文档为准):
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.x</version>
</dependency>
配置与 MyBatis 类似,Mapper 用 @MapperScan 扫描:
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo
username: root
password: 123456
mybatis-plus:
mapper-locations: classpath*:mapper/**/*.xml
@SpringBootApplication
@MapperScan("com.demo.mapper")
public class App { /* ... */ }
实体与表映射
实体用注解声明表名、主键策略与字段映射(MP 默认开启下划线转驼峰):
@TableName("user") // 对应表 user
public class User {
@TableId(type = IdType.AUTO) // 主键:数据库自增;分布式用 ASSIGN_ID 雪花
private Long id;
private String name;
private Integer status;
// getter/setter 省略
}
BaseMapper:单表 CRUD 免 SQL
Mapper 接口继承 BaseMapper,立刻拥有一整套单表方法:
public interface UserMapper extends BaseMapper<User> { }
UserMapper mapper = ...; // 由 Spring 注入
mapper.insert(user); // 新增,id 自动回填
User u = mapper.selectById(1L); // 按主键查
mapper.updateById(user); // 按主键更新(null 字段不更新)
mapper.deleteById(1L); // 按主键删除
List<User> list = mapper.selectList(null); // 查全表
方法按语义分组:insert / delete(byId、byMap、byWrapper)/ update(byId、byWrapper)/ select(byId、one、count、list、maps、page)。多条件查询传"条件构造器 Wrapper"(下一章专讲);批查/批删方法名随版本演进(旧 selectBatchIds 到新 selectByIds 等),以官方文档为准。
Service 封装:IService + ServiceImpl
业务层继承官方封装好的 Service 基类,连 Mapper 注入都省了:
public interface UserService extends IService<User> { }
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService { }
Service 层直接调用增强方法:
@Autowired private UserService userService;
userService.saveBatch(userList); // 批量新增:内部拆批执行
User u = userService.getById(1L);
List<User> list = userService.list(
Wrappers.<User>lambdaQuery().eq(User::getStatus, 1));
// 链式查询语法糖
User one = userService.lambdaQuery()
.eq(User::getName, "小明").one();
boolean ok = userService.lambdaUpdate()
.eq(User::getId, 1L).set(User::getStatus, 0).update();
ServiceImpl 的 CRUD 具备单表 SQL 自动注入能力,MyBatis 原有 XML/注解扩展照常可用,事务注解也照常生效。
MyBatis-Plus 的价值一句话:单表操作交给 BaseMapper/IService,复杂查询仍走你熟悉的 XML。先跑通"实体 + Mapper + Service"最小闭环,再进阶条件构造器与插件。