假设我们有一个简单的微服务项目,需要对 User
实体进行基本的数据库操作。
场景一:使用原生 MyBatis 的开发流程 (作为对比)
-
定义实体类 (Entity):
// package com.yourcompany.usermicroservice.entity; public class User {private Long id;private String name;private Integer age;// Getters and Setters... }
-
定义 Mapper 接口: 需要手动声明每一个 CRUD 方法。
// package com.yourcompany.usermicroservice.mapper; import com.yourcompany.usermicroservice.entity.User; import org.apache.ibatis.annotations.Mapper; import java.util.List;@Mapper // Or use @MapperScan in application class public interface UserMapper {int insert(User user);User selectById(Long id);List<User> selectList(); // Example for list queryint updateById(User user);int deleteById(Long id); }
-
编写 Mapper XML 文件: 需要为接口中的每个方法编写对应的 SQL 语句。
<!-- src/main/resources/mapper/UserMapper.xml --> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.yourcompany.usermicroservice.mapper.UserMapper"><insert id="insert" parameterType="com.yourcompany.usermicroservice.entity.User" useGeneratedKeys="true" keyProperty="id">INSERT INTO user (name, age) VALUES (#{name}, #{age})</insert><select id="selectById" resultType="com.yourcompany.usermicroservice.entity.User">SELECT id, name, age FROM user WHERE id = #{id}</select><select id="selectList" resultType="com.yourcompany.usermicroservice.entity.User">SELECT id, name, age FROM user</select><update id="updateById" parameterType="com.yourcompany.usermicroservice.entity.User">UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}</update><delete id="deleteById">DELETE FROM user WHERE id = #{id}</delete> </mapper>
-
配置 (application.yml): 需要指定 XML 位置等。
mybatis:mapper-locations: classpath*:/mapper/**/*.xmltype-aliases-package: com.yourcompany.usermicroservice.entity
原生 MyBatis 的痛点:
- 代码冗余: 每个实体都需要编写大量的 CRUD 接口方法和 SQL 语句。
- 开发效率低: 编写、调试这些基础 SQL 非常耗时。
- 易出错: 手写 SQL 容易出现拼写错误、字段遗漏等问题。
场景二:使用 MyBatis-Plus BaseMapper
的开发流程 (加速体现)
-
定义实体类 (Entity): 可以使用 MP 的注解优化。
// package com.yourcompany.usermicroservice.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName;@TableName("user") // 显式指定表名 (可选, 如果类名与表名不一致) public class User {@TableId(type = IdType.AUTO) // 指定主键和策略 (AUTO 为自增)private Long id;private String name;private Integer age;// Getters and Setters... }
-
定义 Mapper 接口: 只需继承
BaseMapper<User>
即可,无需声明任何 CRUD 方法!// package com.yourcompany.usermicroservice.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yourcompany.usermicroservice.entity.User; import org.apache.ibatis.annotations.Mapper;@Mapper // Or use @MapperScan public interface UserMapper extends BaseMapper<User> {// 无需在此处声明 insert, selectById, updateById, deleteById 等方法!// BaseMapper 已经提供了这些方法的实现。// 我们可以在这里添加自定义的、BaseMapper 没有提供的复杂查询方法// List<User> findUsersWithComplexCondition(...); }
-
编写 Mapper XML 文件: 对于基础 CRUD 操作,完全不需要编写 XML 文件和 SQL 语句! MP 会自动生成。只有当你需要编写
BaseMapper
未提供的复杂 SQL 时,才需要创建 XML 文件并编写对应的<select>
,<update>
等。 -
配置 (application.yml): 配置可以更简洁,如果完全不使用 XML,
mapper-locations
甚至可以省略(但建议保留以备将来扩展)。mybatis-plus: # 使用 mybatis-plus 前缀 (推荐)# mapper-locations: classpath*:/mapper/**/*.xml # 如果有自定义 XML 才需要type-aliases-package: com.yourcompany.usermicroservice.entityglobal-config:db-config:id-type: auto # 全局配置主键策略
MyBatis-Plus BaseMapper
如何实现加速:
-
消除基础 CRUD 代码: 这是最直接的加速点。通过继承
BaseMapper<T>
,我们可以瞬间获得大量预先实现好的、通用的数据访问方法。上例中,我们一行 CRUD 方法声明和 SQL 都没写,但UserMapper
已经具备了完整的单表增删改查能力。开发效率提升是数量级的。// 在 Service 中可以直接使用继承来的方法 // package com.yourcompany.usermicroservice.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.yourcompany.usermicroservice.entity.User; import com.yourcompany.usermicroservice.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List;@Service public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper; // 注入继承了 BaseMapper 的 UserMapper@Overridepublic boolean createUser(User user) {// 直接调用 BaseMapper 提供的方法,无需在 UserMapper 中声明或实现int result = userMapper.insert(user);return result > 0;}@Overridepublic User getUserById(Long id) {// 直接调用 BaseMapper 提供的方法return userMapper.selectById(id);}@Overridepublic List<User> listUsers() {// 查询所有用户,也由 BaseMapper 提供return userMapper.selectList(null); // null 表示无条件查询}@Overridepublic List<User> findUsersByName(String name) {// 使用 Wrapper 配合 BaseMapper 的 selectList 实现简单条件查询QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like("name", name); // WHERE name LIKE '%...%'return userMapper.selectList(queryWrapper);}@Overridepublic Page<User> listUsersByPage(int current, int size) {// 使用分页查询,需要配置 MP 的分页插件Page<User> page = new Page<>(current, size);// selectPage 方法也由 BaseMapper 提供userMapper.selectPage(page, null); // 第二个参数是查询条件 Wrapperreturn page;}@Overridepublic boolean updateUser(User user) {// 直接调用 BaseMapper 提供的方法int result = userMapper.updateById(user);return result > 0;}@Overridepublic boolean deleteUser(Long id) {// 直接调用 BaseMapper 提供的方法int result = userMapper.deleteById(id);return result > 0;}@Overridepublic boolean deleteUsersBatch(List<Long> ids) {// 批量删除也由 BaseMapper 提供int result = userMapper.deleteBatchIds(ids);return result > 0;} }
-
减少错误和提高一致性: 由于基础 SQL 是框架自动生成的,减少了人为编写 SQL 时的拼写错误、语法错误。同时,所有继承
BaseMapper
的 Mapper 都拥有相同的方法,使得整个微服务的数据访问层接口更加统一和规范。 -
快速开发和迭代: 在微服务开发初期或快速迭代时,可以迅速搭建起数据访问层,将精力集中在业务逻辑验证上。即使后期需要更复杂的查询,也可以平滑的补充自定义方法和 XML。
总结:
BaseMapper<T>
通过消除开发者编写基础的 CRUD 代码和 SQL 的负担,直接提供了丰富、标准化的数据访问方法,使得微服务内部数据访问层的开发变得极其高效。我们开发时只需要定义好实体类和继承 BaseMapper
的接口,就可以立即拥有强大的单表操作功能,从而大幅缩短了开发周期,减少代码量,降低错误率。