MyBatis-Plus 中BaseMapper接口是如何加速微服务内部开发的?

假设我们有一个简单的微服务项目,需要对 User 实体进行基本的数据库操作。

场景一:使用原生 MyBatis 的开发流程 (作为对比)

  1. 定义实体类 (Entity):

    java 复制代码
    // package com.yourcompany.usermicroservice.entity;
    public class User {
        private Long id;
        private String name;
        private Integer age;
        // Getters and Setters...
    }
  2. 定义 Mapper 接口: 需要手动声明每一个 CRUD 方法。

    java 复制代码
    // 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 query
        int updateById(User user);
        int deleteById(Long id);
    }
  3. 编写 Mapper XML 文件: 需要为接口中的每个方法编写对应的 SQL 语句。

    xml 复制代码
    <!-- 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>
  4. 配置 (application.yml): 需要指定 XML 位置等。

    yaml 复制代码
    mybatis:
      mapper-locations: classpath*:/mapper/**/*.xml
      type-aliases-package: com.yourcompany.usermicroservice.entity

原生 MyBatis 的痛点:

  • 代码冗余: 每个实体都需要编写大量的 CRUD 接口方法和 SQL 语句。
  • 开发效率低: 编写、调试这些基础 SQL 非常耗时。
  • 易出错: 手写 SQL 容易出现拼写错误、字段遗漏等问题。

场景二:使用 MyBatis-Plus BaseMapper 的开发流程 (加速体现)

  1. 定义实体类 (Entity): 可以使用 MP 的注解优化。

    java 复制代码
    // 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...
    }
  2. 定义 Mapper 接口: 只需继承 BaseMapper<User> 即可,无需声明任何 CRUD 方法!

    java 复制代码
    // 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(...);
    }
  3. 编写 Mapper XML 文件: 对于基础 CRUD 操作,完全不需要编写 XML 文件和 SQL 语句! MP 会自动生成。只有当你需要编写 BaseMapper 未提供的复杂 SQL 时,才需要创建 XML 文件并编写对应的 <select>, <update> 等。

  4. 配置 (application.yml): 配置可以更简洁,如果完全不使用 XML,mapper-locations 甚至可以省略(但建议保留以备将来扩展)。

    yaml 复制代码
    mybatis-plus: # 使用 mybatis-plus 前缀 (推荐)
      # mapper-locations: classpath*:/mapper/**/*.xml # 如果有自定义 XML 才需要
      type-aliases-package: com.yourcompany.usermicroservice.entity
      global-config:
        db-config:
          id-type: auto # 全局配置主键策略

MyBatis-Plus BaseMapper 如何实现加速:

  1. 消除基础 CRUD 代码: 这是最直接的加速点。通过继承 BaseMapper<T>,我们可以瞬间获得 大量预先实现好的、通用的数据访问方法。上例中,我们一行 CRUD 方法声明和 SQL 都没写,但 UserMapper 已经具备了完整的单表增删改查能力。开发效率提升是数量级的。

    java 复制代码
    // 在 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 {
    
        @Autowired
        private UserMapper userMapper; // 注入继承了 BaseMapper 的 UserMapper
    
        @Override
        public boolean createUser(User user) {
            // 直接调用 BaseMapper 提供的方法,无需在 UserMapper 中声明或实现
            int result = userMapper.insert(user);
            return result > 0;
        }
    
        @Override
        public User getUserById(Long id) {
            // 直接调用 BaseMapper 提供的方法
            return userMapper.selectById(id);
        }
    
        @Override
        public List<User> listUsers() {
            // 查询所有用户,也由 BaseMapper 提供
            return userMapper.selectList(null); // null 表示无条件查询
        }
    
        @Override
        public List<User> findUsersByName(String name) {
            // 使用 Wrapper 配合 BaseMapper 的 selectList 实现简单条件查询
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name", name); // WHERE name LIKE '%...%'
            return userMapper.selectList(queryWrapper);
        }
    
        @Override
        public Page<User> listUsersByPage(int current, int size) {
            // 使用分页查询,需要配置 MP 的分页插件
            Page<User> page = new Page<>(current, size);
            // selectPage 方法也由 BaseMapper 提供
            userMapper.selectPage(page, null); // 第二个参数是查询条件 Wrapper
            return page;
        }
    
    
        @Override
        public boolean updateUser(User user) {
            // 直接调用 BaseMapper 提供的方法
            int result = userMapper.updateById(user);
            return result > 0;
        }
    
        @Override
        public boolean deleteUser(Long id) {
            // 直接调用 BaseMapper 提供的方法
            int result = userMapper.deleteById(id);
            return result > 0;
        }
    
        @Override
        public boolean deleteUsersBatch(List<Long> ids) {
            // 批量删除也由 BaseMapper 提供
            int result = userMapper.deleteBatchIds(ids);
            return result > 0;
        }
    }
  2. 减少错误和提高一致性: 由于基础 SQL 是框架自动生成的,减少了人为编写 SQL 时的拼写错误、语法错误。同时,所有继承 BaseMapper 的 Mapper 都拥有相同的方法,使得整个微服务的数据访问层接口更加统一和规范。

  3. 快速开发和迭代: 在微服务开发初期或快速迭代时,可以迅速搭建起数据访问层,将精力集中在业务逻辑验证上。即使后期需要更复杂的查询,也可以平滑的补充自定义方法和 XML。

总结:

BaseMapper<T> 通过消除开发者编写基础的 CRUD 代码和 SQL 的负担 ,直接提供了丰富、标准化的数据访问方法,使得微服务内部数据访问层的开发变得极其高效。我们开发时只需要定义好实体类和继承 BaseMapper 的接口,就可以立即拥有强大的单表操作功能,从而大幅缩短了开发周期,减少代码量,降低错误率。

相关推荐
执卿13 分钟前
使用Hilt重构项目
架构
SimonKing15 分钟前
吊打面试官系列:Spring为什么不推荐使用字段依赖注入?
java·后端·架构
用户6965180071627 分钟前
mybatis分页插件
mybatis
season_zhu1 小时前
Swift:优雅又强大的语法糖——Then库
ios·架构·swift
hstar95272 小时前
二、即时通讯系统设计经验
java·架构
江梦寻3 小时前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
Zfox_7 小时前
Redis:Hash数据类型
服务器·数据库·redis·缓存·微服务·哈希算法
打码人的日常分享11 小时前
物联网智慧医院建设方案(PPT)
大数据·物联网·架构·流程图·智慧城市·制造
白水baishui11 小时前
搭建强化推荐的决策服务架构
架构·推荐系统·强化学习·决策服务·服务架构
何双新11 小时前
第23讲、Odoo18 邮件系统整体架构
ai·架构