后山一绝 發表於 2026-1-12 11:30:27

MyBatis映射器模块最佳实践

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>一、MyBatis整体架构与映射器模块</li><ul class="second_class_ul"><li>1.1 映射器模块的核心职责</li><li>1.2 为什么需要Mapper?</li><li>1.3 Mapper的使用方式</li></ul><li>二、Mapper接口架构</li><ul class="second_class_ul"><li>2.1 Mapper接口定义</li><li>2.2 Mapper接口特点</li><li>2.3 MapperRegistry注册中心</li></ul><li>三、SQL语句映射</li><ul class="second_class_ul"><li>3.1 XML配置方式</li><li>3.2 注解配置方式</li><li>3.3 混合配置方式</li></ul><li>四、动态代理实现</li><ul class="second_class_ul"><li>4.1 MapperProxyFactory代理工厂</li><li>4.2 MapperProxy代理类</li><li>4.3 MapperMethod方法执行器</li><li>4.4 代理执行流程</li></ul><li>五、Mapper注册流程</li><ul class="second_class_ul"><li>5.1 注册方式</li></ul><li>六、Mapper执行流程</li><ul class="second_class_ul"><li>6.1 完整执行流程</li><li>6.2 详细执行步骤</li><li>6.3 执行时序图</li><li>6.4 异常处理</li></ul><li>七、最佳实践</li><ul class="second_class_ul"><li>7.1 Mapper设计建议</li><li>7.2 性能优化建议</li><li>7.3 常见问题解决</li></ul><li>八、总结</li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>一、MyBatis整体架构与映射器模块</h2>
<p>在深入映射器模块之前,我们先了解MyBatis的整体架构,以及映射器模块在其中的重要地位。</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026011211232521.jpg" /></p>
<p>从架构图可以看出,MyBatis采用了分层架构设计,而映射器模块(Mapper Interface)位于接口层,是用户与MyBatis交互的主要入口。它通过接口定义数据库操作,结合XML或注解配置SQL语句,利用动态代理技术自动实现接口,让开发者以面向对象的方式操作数据库。</p>
<p class="maodian"></p><h3>1.1 映射器模块的核心职责</h3>
<p>映射器模块主要承担以下核心职责:<br />定义数据库操作接口 - 通过Java接口定义CRUD操作<br />SQL语句映射 - 将接口方法与SQL语句关联<br />参数映射 - 将方法参数转换为SQL参数<br />结果映射 - 将查询结果映射为Java对象<br />动态代理实现 - 自动生成接口实现类</p>
<p class="maodian"></p><h3>1.2 为什么需要Mapper?</h3>
<p>传统的JDBC编程存在以下问题:</p>
<div class="jb51code"><pre class="brush:java;">//传统JDBC方式
String sql = "SELECT * FROM t_user WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();
// 手动解析ResultSet并映射为对象...
</pre></div>
<p>这种方式的问题:<br />1、SQL分散在代码中,难以维护<br />2、参数设置和结果映射都是手工操作<br />3、容易出现类型转换错误<br />4、代码重复度高</p>
<p>使用Mapper后:</p>
<div class="jb51code"><pre class="brush:java;">//Mapper方式
@Select("SELECT * FROM t_user WHERE id = #{id}")
User selectById(Long id);
// 使用
User user = userMapper.selectById(1L);</pre></div>
<p>优势:<br />SQL与代码分离,易于维护<br />自动参数映射和结果映射<br />类型安全<br />代码简洁</p>
<p class="maodian"></p><h3>1.3 Mapper的使用方式</h3>
<p>MyBatis支持两种Mapper配置方式:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026011211232511.png" /></p>
<p class="maodian"></p><h2>二、Mapper接口架构</h2>
<p>MyBatis的映射器模块采用了接口+配置的设计模式。</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026011211232599.jpg" /></p>
<p class="maodian"></p><h3>2.1 Mapper接口定义</h3>
<p>Mapper是一个普通的Java接口,无需实现类:</p>
<div class="jb51code"><pre class="brush:java;">public interface UserMapper {
    // 查询单个对象
    User selectById(Long id);
    // 查询列表
    List&lt;User&gt; selectAll();
    // 插入
    int insert(User user);
    // 更新
    int update(User user);
    // 删除
    int deleteById(Long id);
    // 复杂查询
    List&lt;User&gt; selectByCondition(@Param("name") String name,
                                  @Param("age") Integer age);
}</pre></div>
<p class="maodian"></p><h3>2.2 Mapper接口特点</h3>
<p>无需实现类 - MyBatis通过动态代理自动生成实现<br />方法名与SQL ID对应 - 接口方法名即为MappedStatement的ID<br />参数灵活 - 支持单参数、多参数、对象参数<br />返回值多样 - 支持单对象、集合、Map等</p>
<p class="maodian"></p><h3>2.3 MapperRegistry注册中心</h3>
<p>MyBatis维护了Mapper接口的注册中心:</p>
<div class="jb51code"><pre class="brush:java;">public class MapperRegistry {
    // Configuration对象
    private final Configuration config;
    // Mapper接口与代理工厂的映射
    private final Map&lt;Class&lt;?&gt;, MapperProxyFactory&lt;?&gt;&gt; knownMappers =
      new HashMap&lt;&gt;();
    public MapperRegistry(Configuration config) {
      this.config = config;
    }
    // 添加Mapper接口
    public &lt;T&gt; void addMapper(Class&lt;T&gt; type) {
      if (type.isInterface()) {
            if (hasMapper(type)) {
                throw new BindingException(
                  "Type " + type + " is already known to the MapperRegistry."
                );
            }
            boolean loadCompleted = false;
            try {
                // 创建MapperProxyFactory
                knownMappers.put(type, new MapperProxyFactory&lt;&gt;(type));
                // 解析Mapper注解
                MapperAnnotationBuilder parser =
                  new MapperAnnotationBuilder(config, type);
                parser.parse();
                loadCompleted = true;
            } finally {
                if (!loadCompleted) {
                  knownMappers.remove(type);
                }
            }
      }
    }
    // 获取Mapper实例
    public &lt;T&gt; T getMapper(Class&lt;T&gt; type, SqlSession sqlSession) {
      final MapperProxyFactory&lt;T&gt; mapperProxyFactory =
            (MapperProxyFactory&lt;T&gt;) knownMappers.get(type);
      if (mapperProxyFactory == null) {
            throw new BindingException(
                "Type " + type + " is not known to the MapperRegistry."
            );
      }
      try {
            return mapperProxyFactory.newInstance(sqlSession);
      } catch (Exception e) {
            throw new BindingException(
                "Error getting mapper instance. Cause: " + e, e
            );
      }
    }
    // 检查是否已注册
    public &lt;T&gt; boolean hasMapper(Class&lt;T&gt; type) {
      return knownMappers.containsKey(type);
    }
    // 获取所有Mapper接口
    public Collection&lt;Class&lt;?&gt;&gt; getMappers() {
      return Collections.unmodifiableCollection(knownMappers.keySet());
    }
}</pre></div>
<p class="maodian"></p><h2>三、SQL语句映射</h2>
<p>MyBatis提供了灵活的SQL映射方式。</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026011211232553.png" /></p>
<p class="maodian"></p><h3>3.1 XML配置方式</h3>
<div class="jb51code"><pre class="brush:xml;">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;
&lt;mapper namespace="com.example.mapper.UserMapper"&gt;
    &lt;!--结果映射 --&gt;
    &lt;resultMap id="BaseResultMap" type="com.example.entity.User"&gt;
      &lt;id column="id" property="id" jdbcType="BIGINT"/&gt;
      &lt;result column="name" property="name" jdbcType="VARCHAR"/&gt;
      &lt;result column="email" property="email" jdbcType="VARCHAR"/&gt;
      &lt;result column="age" property="age" jdbcType="INTEGER"/&gt;
      &lt;result column="create_time" property="createTime"
                jdbcType="TIMESTAMP"/&gt;
    &lt;/resultMap&gt;
    &lt;!--查询单个用户 --&gt;
    &lt;select id="selectById" resultMap="BaseResultMap"&gt;
      SELECT id, name, email, age, create_time
      FROM t_user
      WHERE id = #{id}
    &lt;/select&gt;
    &lt;!-- 查询所有用户 --&gt;
    &lt;select id="selectAll" resultMap="BaseResultMap"&gt;
      SELECT id, name, email, age, create_time
      FROM t_user
      ORDER BY id
    &lt;/select&gt;
    &lt;!-- 插入用户 --&gt;
    &lt;insert id="insert" parameterType="com.example.entity.User"
            useGeneratedKeys="true" keyProperty="id"&gt;
      INSERT INTO t_user (name, email, age, create_time)
      VALUES (#{name}, #{email}, #{age}, NOW())
    &lt;/insert&gt;
    &lt;!--更新用户 --&gt;
    &lt;update id="update" parameterType="com.example.entity.User"&gt;
      UPDATE t_user
      SET name = #{name},
            email = #{email},
            age = #{age}
      WHERE id = #{id}
    &lt;/update&gt;
    &lt;!--删除用户 --&gt;
    &lt;delete id="deleteById"&gt;
      DELETE FROM t_user
      WHERE id = #{id}
    &lt;/delete&gt;
    &lt;!--动态SQL查询 --&gt;
    &lt;select id="selectByCondition" resultMap="BaseResultMap"&gt;
      SELECT id, name, email, age, create_time
      FROM t_user
      &lt;where&gt;
            &lt;if test="name != null and name != ''"&gt;
                AND name LIKE CONCAT('%', #{name}, '%')
            &lt;/if&gt;
            &lt;if test="age != null"&gt;
                AND age = #{age}
            &lt;/if&gt;
      &lt;/where&gt;
      ORDER BY id
    &lt;/select&gt;
&lt;/mapper&gt;</pre></div>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026011211232549.png" /></p>
<p class="maodian"></p><h3>3.2 注解配置方式</h3>
<div class="jb51code"><pre class="brush:java;">public interface UserMapper {
    @Select("SELECT * FROM t_user WHERE id = #{id}")
    @Results(id = "userResult", value = {
      @Result(property = "id", column = "id", id = true),
      @Result(property = "name", column = "name"),
      @Result(property = "email", column = "email"),
      @Result(property = "age", column = "age"),
      @Result(property = "createTime", column = "create_time")
    })
    User selectById(Long id);
    @Select("SELECT * FROM t_user ORDER BY id")
    List&lt;User&gt; selectAll();
    @Insert("INSERT INTO t_user (name, email, age, create_time) " +
            "VALUES (#{name}, #{email}, #{age}, NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);
    @Update("UPDATE t_user SET name = #{name}, email = #{email}, " +
            "age = #{age} WHERE id = #{id}")
    int update(User user);
    @Delete("DELETE FROM t_user WHERE id = #{id}")
    int deleteById(Long id);
    @Select("&lt;script&gt;" +
            "SELECT * FROM t_user " +
            "&lt;where&gt;" +
            "&lt;if test='name != null'&gt;" +
            "AND name LIKE CONCAT('%', #{name}, '%')" +
            "&lt;/if&gt;" +
            "&lt;if test='age != null'&gt;AND age = #{age}&lt;/if&gt;" +
            "&lt;/where&gt;" +
            "&lt;/script&gt;")
    List&lt;User&gt; selectByCondition(@Param("name") String name,
                                  @Param("age") Integer age);
}</pre></div>
<p class="maodian"></p><h3>3.3 混合配置方式</h3>
<p>XML和注解可以混合使用:</p>
<div class="jb51code"><pre class="brush:java;">public interface UserMapper {
    //注解方式:简单查询
    @Select("SELECT * FROM t_user WHERE id = #{id}")
    User selectById(Long id);
    //XML方式:复杂查询
    List&lt;User&gt; selectByCondition(UserQuery query);
}
&lt;mapper namespace="com.example.mapper.UserMapper"&gt;
    &lt;!-- 复杂查询使用XML --&gt;
    &lt;select id="selectByCondition" resultMap="BaseResultMap"&gt;
      SELECT * FROM t_user
      &lt;where&gt;
            &lt;if test="name != null"&gt;
                AND name LIKE CONCAT('%', #{name}, '%')
            &lt;/if&gt;
            &lt;if test="age != null"&gt;
                AND age = #{age}
            &lt;/if&gt;
      &lt;/where&gt;
    &lt;/select&gt;
&lt;/mapper&gt;</pre></div>
<p class="maodian"></p><h2>四、动态代理实现</h2>
<p>MyBatis通过JDK动态代理自动实现Mapper接口。</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026011211232566.png" /></p>
<p class="maodian"></p><h3>4.1 MapperProxyFactory代理工厂</h3>
<div class="jb51code"><pre class="brush:java;">public class MapperProxyFactory&lt;T&gt; {
    // Mapper接口类型
    private final Class&lt;T&gt; mapperInterface;
    // 方法缓存
    private final Map&lt;Method, MapperMethod&gt; methodCache =
      new ConcurrentHashMap&lt;&gt;();
    public MapperProxyFactory(Class&lt;T&gt; mapperInterface) {
      this.mapperInterface = mapperInterface;
    }
    //创建代理实例
    public T newInstance(SqlSession sqlSession) {
      final MapperProxy&lt;T&gt; mapperProxy = new MapperProxy&lt;&gt;(
            sqlSession, mapperInterface, methodCache
      );
      return newInstance(mapperProxy);
    }
    @SuppressWarnings("unchecked")
    protected T newInstance(MapperProxy&lt;T&gt; mapperProxy) {
      // 使用JDK动态代理创建代理对象
      return (T) Proxy.newProxyInstance(
            mapperInterface.getClassLoader(),
            new Class[]{mapperInterface},
            mapperProxy
      );
    }
    public Class&lt;T&gt; getMapperInterface() {
      return mapperInterface;
    }
    public Map&lt;Method, MapperMethod&gt; getMethodCache() {
      return methodCache;
    }
}</pre></div>
<p class="maodian"></p><h3>4.2 MapperProxy代理类</h3>
<div class="jb51code"><pre class="brush:java;">public class MapperProxy&lt;T&gt; implements InvocationHandler {
    private final SqlSession sqlSession;
    private final Class&lt;T&gt; mapperInterface;
    private final Map&lt;Method, MapperMethod&gt; methodCache;
    public MapperProxy(SqlSession sqlSession, Class&lt;T&gt; mapperInterface,
                     Map&lt;Method, MapperMethod&gt; methodCache) {
      this.sqlSession = sqlSession;
      this.mapperInterface = mapperInterface;
      this.methodCache = methodCache;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {
      // 1.如果是Object类的方法,直接执行
      if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {
                throw ExceptionUtil.unwrapThrowable(t);
            }
      }
      //2.获取MapperMethod并执行
      final MapperMethod mapperMethod = cachedMapperMethod(method);
      return mapperMethod.execute(sqlSession, args);
    }
    //缓存MapperMethod
    private MapperMethod cachedMapperMethod(Method method) {
      return methodCache.computeIfAbsent(method,
            k -&gt; new MapperMethod(mapperInterface, method,
                                  sqlSession.getConfiguration())
      );
    }
}</pre></div>
<p class="maodian"></p><h3>4.3 MapperMethod方法执行器</h3>
<div class="jb51code"><pre class="brush:java;">public class MapperMethod {
    // SqlCommand封装了SQL命令信息
    private final SqlCommand command;
    // MethodSignature封装了方法签名信息
    private final MethodSignature method;
    public MapperMethod(Class&lt;?&gt; mapperInterface, Method method,
                     Configuration config) {
      this.command = new SqlCommand(config, mapperInterface, method);
      this.method = new MethodSignature(config, mapperInterface, method);
    }
    public Object execute(SqlSession sqlSession, Object[] args) {
      Object result;
      switch (command.getType()) {
            case INSERT: {
                //插入操作
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(
                  sqlSession.insert(command.getName(), param)
                );
                break;
            }
            case UPDATE: {
                //更新操作
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(
                  sqlSession.update(command.getName(), param)
                );
                break;
            }
            case DELETE: {
                //删除操作
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(
                  sqlSession.delete(command.getName(), param)
                );
                break;
            }
            case SELECT:
                if (method.returnsVoid() &amp;&amp; method.hasResultHandler()) {
                  // 有ResultHandler的查询
                  executeWithResultHandler(sqlSession, args);
                  result = null;
                } else if (method.returnsMany()) {
                  //返回集合
                  result = executeForMany(sqlSession, args);
                } else if (method.returnsMap()) {
                  //返回Map
                  result = executeForMap(sqlSession, args);
                } else if (method.returnsCursor()) {
                  //返回Cursor
                  result = executeForCursor(sqlSession, args);
                } else {
                  //返回单个对象
                  Object param = method.convertArgsToSqlCommandParam(args);
                  result = sqlSession.selectOne(command.getName(), param);
                  if (method.returnsOptional() &amp;&amp;
                        (result == null ||
                         !method.getReturnType().equals(result.getClass()))) {
                        result = Optional.ofNullable(result);
                  }
                }
                break;
            case FLUSH:
                result = sqlSession.flushStatements();
                break;
            default:
                throw new BindingException(
                  "Unknown execution method for: " + command.getName()
                );
      }
      if (result == null &amp;&amp; method.getReturnType().isPrimitive() &amp;&amp;
            !method.returnsVoid()) {
            throw new BindingException(
                "Mapper method '" + command.getName() +
                "' attempted to return null from a method with " +
                "a primitive return type (" + method.getReturnType() + ")."
            );
      }
      return result;
    }
    // 执行返回多条的查询
    private &lt;E&gt; Object executeForMany(SqlSession sqlSession, Object[] args) {
      List&lt;E&gt; result;
      Object param = method.convertArgsToSqlCommandParam(args);
      if (method.hasRowBounds()) {
            RowBounds rowBounds = method.extractRowBounds(args);
            result = sqlSession.selectList(
                command.getName(), param, rowBounds
            );
      } else {
            result = sqlSession.selectList(command.getName(), param);
      }
      return result;
    }
    // 执行返回Map的查询
    private &lt;K, V&gt; Map&lt;K, V&gt; executeForMap(SqlSession sqlSession,
                                          Object[] args) {
      Object param = method.convertArgsToSqlCommandParam(args);
      Map&lt;K, V&gt; result;
      if (method.hasRowBounds()) {
            RowBounds rowBounds = method.extractRowBounds(args);
            result = sqlSession.selectMap(
                command.getName(), param, method.getMapKey(), rowBounds
            );
      } else {
            result = sqlSession.selectMap(
                command.getName(), param, method.getMapKey()
            );
      }
      return result;
    }
    // 处理行数结果
    private Object rowCountResult(int rowCount) {
      final Object result;
      if (method.returnsVoid()) {
            result = null;
      } else if (Integer.TYPE.equals(method.getReturnType()) ||
                   Integer.class.equals(method.getReturnType())) {
            result = rowCount;
      } else if (Long.TYPE.equals(method.getReturnType()) ||
                   Long.class.equals(method.getReturnType())) {
            result = (long) rowCount;
      } else if (Boolean.TYPE.equals(method.getReturnType()) ||
                   Boolean.class.equals(method.getReturnType())) {
            result = rowCount &gt; 0;
      } else {
            throw new BindingException(
                "Mapper method '" + command.getName() +
                "' has an unsupported return type: " +
                method.getReturnType()
            );
      }
      return result;
    }
    //内部类:SqlCommand
    public static class SqlCommand {
      private final String name;
      private final SqlCommandType type;
      public SqlCommand(Configuration configuration,
                         Class&lt;?&gt; mapperInterface, Method method) {
            final String methodName = method.getName();
            final Class&lt;?&gt; declaringClass = method.getDeclaringClass();
            // 解析MappedStatement
            MappedStatement ms = resolveMappedStatement(
                mapperInterface, methodName, declaringClass, configuration
            );
            if (ms == null) {
                if (method.getAnnotation(Flush.class) != null) {
                  name = null;
                  type = SqlCommandType.FLUSH;
                } else {
                  throw new BindingException(
                        "Invalid bound statement (not found): " +
                        mapperInterface.getName() + "." + methodName
                  );
                }
            } else {
                name = ms.getId();
                type = ms.getSqlCommandType();
                if (type == SqlCommandType.UNKNOWN) {
                  throw new BindingException(
                        "Unknown execution method for: " + name
                  );
                }
            }
      }
      private MappedStatement resolveMappedStatement(
            Class&lt;?&gt; mapperInterface, String methodName,
            Class&lt;?&gt; declaringClass, Configuration configuration) {
            String statementId = mapperInterface.getName() + "." + methodName;
            if (configuration.hasStatement(statementId)) {
                return configuration.getMappedStatement(statementId);
            }
            return null;
      }
      public String getName() {
            return name;
      }
      public SqlCommandType getType() {
            return type;
      }
    }
    //内部类:MethodSignature
    public static class MethodSignature {
      private final boolean returnsMany;
      private final boolean returnsMap;
      private final boolean returnsVoid;
      private final boolean returnsCursor;
      private final boolean returnsOptional;
      private final Class&lt;?&gt; returnType;
      private final String mapKey;
      private final Integer resultHandlerIndex;
      private final Integer rowBoundsIndex;
      private final ParamNameResolver paramNameResolver;
      public MethodSignature(Configuration configuration,
                              Class&lt;?&gt; mapperInterface, Method method) {
            Type resolvedReturnType = typeParameterResolver(method);
            // 解析返回类型
            if (resolvedReturnType instanceof Void) {
                this.returnsVoid = true;
            } else if (Collection.class.isAssignableFrom(
                (Class&lt;?&gt;) resolvedReturnType) ||
                resolvedReturnType.isArray()) {
                this.returnsMany = true;
            } else if (Map.class.isAssignableFrom(
                (Class&lt;?&gt;) resolvedReturnType)) {
                this.returnsMap = true;
            } else {
                this.returnsMany = false;
                this.returnsMap = false;
            }
            // ... 省略其他初始化代码
      }
      public Object convertArgsToSqlCommandParam(Object[] args) {
            return paramNameResolver.getNamedParams(args);
      }
      public boolean hasRowBounds() {
            return rowBoundsIndex != null;
      }
    }
}</pre></div>
<p class="maodian"></p><h3>4.4 代理执行流程</h3>
<div class="jb51code"><pre class="brush:plain;">1. 调用Mapper接口方法
   ↓
2. 触发MapperProxy.invoke()
   ↓
3. 获取或创建MapperMethod
   ↓
4. 执行MapperMethod.execute()
   ↓
5. 根据SQL类型调用SqlSession方法
   ↓
6. Executor执行SQL
   ↓
7. 返回结果</pre></div>
<p class="maodian"></p><h2>五、Mapper注册流程</h2>
<p>Mapper接口需要注册到MyBatis才能使用。</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026011211232553.png" /></p>
<p class="maodian"></p><h3>5.1 注册方式</h3>
<div class="jb51code"><pre class="brush:java;">&lt;configuration&gt;
    &lt;!-- 注册Mapper接口 --&gt;
    &lt;mappers&gt;
      &lt;!--使用类路径 --&gt;
      &lt;mapper class="com.example.mapper.UserMapper"/&gt;
      &lt;!--使用包扫描 --&gt;
      &lt;package name="com.example.mapper"/&gt;
      &lt;!--使用XML资源路径 --&gt;
      &lt;mapper resource="com/example/mapper/UserMapper.xml"/&gt;
    &lt;/mappers&gt;
&lt;/configuration&gt;
// 创建Configuration
Configuration configuration = new Configuration();
// 注册Mapper接口
configuration.addMapper(UserMapper.class);
configuration.addMapper(OrderMapper.class);
// 或者通过MapperRegistry
MapperRegistry mapperRegistry = configuration.getMapperRegistry();
mapperRegistry.addMapper(UserMapper.class);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 通过InputStream
SqlSessionFactory factory = builder.build(inputStream);
// 通过Configuration
Environment environment = new Environment("development", ...);
Configuration configuration = new Configuration(environment);
configuration.addMapper(UserMapper.class);
SqlSessionFactory factory =
    new SqlSessionFactoryBuilder().build(configuration);
public class Configuration {
    protected final MapperRegistry mapperRegistry =
      new MapperRegistry(this);
    // 添加Mapper
    public &lt;T&gt; void addMapper(Class&lt;T&gt; type) {
      mapperRegistry.addMapper(type);
    }
    // 获取Mapper
    public &lt;T&gt; T getMapper(Class&lt;T&gt; type, SqlSession sqlSession) {
      return mapperRegistry.getMapper(type, sqlSession);
    }
    // 检查Mapper是否存在
    public boolean hasMapper(Class&lt;?&gt; type) {
      return mapperRegistry.hasMapper(type);
    }
    public MapperRegistry getMapperRegistry() {
      return mapperRegistry;
    }
}
public class MapperScannerConfigurer {
    // 扫描包路径
    private String basePackage;
    public void postProcessBeanDefinitionRegistry(
      BeanDefinitionRegistry registry) {
      // 创建扫描器
      ClassPathMapperScanner scanner =
            new ClassPathMapperScanner(registry);
      // 设置扫描包
      scanner.scan(StringUtils.tokenizeToStringArray(
            this.basePackage,
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS
      ));
    }
}
class ClassPathMapperScanner extends ClassPathBeanDefinitionScanner {
    @Override
    public Set&lt;BeanDefinitionHolder&gt; doScan(String... basePackages) {
      Set&lt;BeanDefinitionHolder&gt; beanDefinitions =
            super.doScan(basePackages);
      if (beanDefinitions.isEmpty()) {
            logger.warn("No MyBatis mapper was found in '" +
                Arrays.toString(basePackages) +
                "' package. Please check your configuration.");
      } else {
            // 处理BeanDefinition
            processBeanDefinitions(beanDefinitions);
      }
      return beanDefinitions;
    }
    private void processBeanDefinitions(
      Set&lt;BeanDefinitionHolder&gt; beanDefinitions) {
      GenericBeanDefinition definition;
      for (BeanDefinitionHolder holder : beanDefinitions) {
            definition = (GenericBeanDefinition) holder.getBeanDefinition();
            // 设置BeanClass为MapperFactoryBean
            definition.getConstructorArgumentValues()
                .addGenericArgumentValue(definition.getBeanClassName());
            definition.setBeanClass(this.mapperFactoryBean.getClass());
            // ... 省略其他配置
      }
    }
}</pre></div>
<p class="maodian"></p><h2>六、Mapper执行流程</h2>
<p>理解Mapper的执行流程对于调试和优化至关重要。</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026011211232563.png" /></p>
<p class="maodian"></p><h3>6.1 完整执行流程</h3>
<div class="jb51code"><pre class="brush:java;">//1.获取SqlSession
SqlSession session = sqlSessionFactory.openSession();
try {
    //2.获取Mapper代理对象
    UserMapper userMapper = session.getMapper(UserMapper.class);
    //3.调用Mapper方法
    User user = userMapper.selectById(1L);
    //4.使用结果
    System.out.println(user);
    //5.提交事务
    session.commit();
} finally {
    //6.关闭Session
    session.close();
}</pre></div>
<p class="maodian"></p><h3>6.2 详细执行步骤</h3>
<p>步骤1: 获取Mapper代理对象</p>
<div class="jb51code"><pre class="brush:java;">session.getMapper(UserMapper.class)

configuration.getMapper(UserMapper.class, this)

mapperRegistry.getMapper(UserMapper.class, this)

mapperProxyFactory.newInstance(this)

Proxy.newProxyInstance(...) → 创建代理对象</pre></div>
<p>步骤2: 调用Mapper方法</p>
<div class="jb51code"><pre class="brush:java;">   userMapper.selectById(1L)
    ↓
    MapperProxy.invoke(proxy, method, args)
    ↓
    cachedMapperMethod(method)
    ↓
    mapperMethod.execute(sqlSession, args)</pre></div>
<p>步骤3: 执行SQL</p>
<div class="jb51code"><pre class="brush:java;">SqlCommandType.SELECT

sqlSession.selectOne(statementId, param)

executor.query(ms, param, rowBounds, resultHandler)

创建CacheKey

查询缓存

查询数据库

映射结果</pre></div>
<p>步骤4: 返回结果</p>
<div class="jb51code"><pre class="brush:java;"> 处理ResultSet
    ↓
    ObjectFactory创建对象
    ↓
    ResultHandler映射
    ↓
    返回User对象
</pre></div>
<p class="maodian"></p><h3>6.3 执行时序图</h3>
<div class="jb51code"><pre class="brush:java;">应用 → MapperProxy → MapperMethod → SqlSession →
Executor → StatementHandler → Database
</pre></div>
<p class="maodian"></p><h3>6.4 异常处理</h3>
<div class="jb51code"><pre class="brush:java;">try {
    User user = userMapper.selectById(1L);
} catch (PersistenceException e) {
    // 持久化异常
    Throwable cause = e.getCause();
    if (cause instanceof SQLException) {
      // 处理SQL异常
      SQLException sqlEx = (SQLException) cause;
      System.out.println("SQL Error: " + sqlEx.getMessage());
    }
} catch (BindingException e) {
    // 绑定异常:Mapper方法未找到
    System.out.println("Mapper method not found: " + e.getMessage());
}
</pre></div>
<p class="maodian"></p><h2>七、最佳实践</h2>
<p class="maodian"></p><h3>7.1 Mapper设计建议</h3>
<p>单一职责 - 每个Mapper对应一张表<br />命名规范 - 接口名与实体名对应<br />方法命名 - 使用语义化的方法名<br />参数设计 - 使用@Param注解明确参数名</p>
<p class="maodian"></p><h3>7.2 性能优化建议</h3>
<p>合理使用缓存 - 二级缓存提升性能<br />避免N+1查询 - 使用关联查询<br />分页查询 - 使用RowBounds或PageHelper<br />批量操作 - 使用BatchExecutor</p>
<p class="maodian"></p><h3>7.3 常见问题解决</h3>
<div class="jb51code"><pre class="brush:java;">//错误:多参数未使用@Param
List&lt;User&gt; select(String name, Integer age);
//正确:使用@Param
List&lt;User&gt; select(@Param("name") String name,
               @Param("age") Integer age);
&lt;!--正确:使用resultMap --&gt;
&lt;resultMap id="BaseResultMap" type="User"&gt;
    &lt;id column="id" property="id"/&gt;
    &lt;result column="user_name" property="name"/&gt;
&lt;/resultMap&gt;
&lt;select id="selectById" resultMap="BaseResultMap"&gt;
    SELECT id, user_name FROM t_user WHERE id = #{id}
&lt;/select&gt;</pre></div>
<p class="maodian"></p><h2>八、总结</h2>
<p>MyBatis的映射器模块通过接口+配置的方式,实现了优雅的数据库操作。<br />Mapper接口 - 定义数据库操作方法<br />SQL映射 - XML或注解配置SQL语句<br />动态代理 - JDK动态代理自动实现接口<br />MapperProxy - 拦截方法调用并执行SQL<br />MapperMethod - 封装方法执行逻辑</p>
<p>到此这篇关于MyBatis映射器模块最佳实践的文章就介绍到这了,更多相关MyBatis映射器模块内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>mybatis映射器配置小结</li><li>深入浅出MyBatis映射器</li><li>Spring整合Mybatis方式之注册映射器</li><li>MyBatis中XML映射器的实现</li><li>MyBatis Mapper映射器的具体用法</li><li>MyBatis映射器mapper快速入门教程</li><li>MyBatis 引入映射器的方法</li><li>详解Java的MyBatis框架与Spring框架整合中的映射器注入</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: MyBatis映射器模块最佳实践