从源码层面深入理解MyBatis Mapper的设计与实现
一、MyBatis整体架构与映射器模块
在深入映射器模块之前,我们先了解MyBatis的整体架构,以及映射器模块在其中的重要地位。

从架构图可以看出,MyBatis采用了分层架构设计,而映射器模块(Mapper Interface)位于接口层,是用户与MyBatis交互的主要入口。它通过接口定义数据库操作,结合XML或注解配置SQL语句,利用动态代理技术自动实现接口,让开发者以面向对象的方式操作数据库。
1.1 映射器模块的核心职责
映射器模块主要承担以下核心职责:
sql
✅ 定义数据库操作接口 - 通过Java接口定义CRUD操作
✅ SQL语句映射 - 将接口方法与SQL语句关联
✅ 参数映射 - 将方法参数转换为SQL参数
✅ 结果映射 - 将查询结果映射为Java对象
✅ 动态代理实现 - 自动生成接口实现类
1.2 为什么需要Mapper?
传统的JDBC编程存在以下问题:
ini
//传统JDBC方式
String sql = "SELECT * FROM t_user WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();
// 手动解析ResultSet并映射为对象...
这种方式的问题:
sql
1、SQL分散在代码中,难以维护
2、参数设置和结果映射都是手工操作
3、容易出现类型转换错误
4、代码重复度高
使用Mapper后:
java
//Mapper方式
@Select("SELECT * FROM t_user WHERE id = #{id}")
User selectById(Long id);
// 使用
User user = userMapper.selectById(1L);
优势:
sql
✅ SQL与代码分离,易于维护
✅ 自动参数映射和结果映射
✅ 类型安全
✅ 代码简洁
1.3 Mapper的使用方式
MyBatis支持两种Mapper配置方式:
| 配置方式 | 说明 | 适用场景 |
|---|---|---|
| XML配置 | SQL语句在XML文件中 | 复杂SQL、需要动态SQL |
| 注解配置 | SQL语句在注解中 | 简单SQL、快速开发 |
二、Mapper接口架构
MyBatis的映射器模块采用了接口+配置的设计模式。

2.1 Mapper接口定义
Mapper是一个普通的Java接口,无需实现类:
less
public interface UserMapper {
// 查询单个对象
User selectById(Long id);
// 查询列表
List<User> selectAll();
// 插入
int insert(User user);
// 更新
int update(User user);
// 删除
int deleteById(Long id);
// 复杂查询
List<User> selectByCondition(@Param("name") String name,
@Param("age") Integer age);
}
2.2 Mapper接口特点
javascript
1️⃣ 无需实现类 - MyBatis通过动态代理自动生成实现
2️⃣ 方法名与SQL ID对应 - 接口方法名即为MappedStatement的ID
3️⃣ 参数灵活 - 支持单参数、多参数、对象参数
4️⃣ 返回值多样 - 支持单对象、集合、Map等
2.3 MapperRegistry注册中心
MyBatis维护了Mapper接口的注册中心:
typescript
public class MapperRegistry {
// Configuration对象
private final Configuration config;
// Mapper接口与代理工厂的映射
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers =
new HashMap<>();
public MapperRegistry(Configuration config) {
this.config = config;
}
// 添加Mapper接口
public <T> void addMapper(Class<T> 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<>(type));
// 解析Mapper注解
MapperAnnotationBuilder parser =
new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
// 获取Mapper实例
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory =
(MapperProxyFactory<T>) 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 <T> boolean hasMapper(Class<T> type) {
return knownMappers.containsKey(type);
}
// 获取所有Mapper接口
public Collection<Class<?>> getMappers() {
return Collections.unmodifiableCollection(knownMappers.keySet());
}
}
三、SQL语句映射
MyBatis提供了灵活的SQL映射方式。

3.1 XML配置方式
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.example.mapper.UserMapper">
<!--结果映射 -->
<resultMap id="BaseResultMap" type="com.example.entity.User">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="email" property="email" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
<result column="create_time" property="createTime"
jdbcType="TIMESTAMP"/>
</resultMap>
<!--查询单个用户 -->
<select id="selectById" resultMap="BaseResultMap">
SELECT id, name, email, age, create_time
FROM t_user
WHERE id = #{id}
</select>
<!-- 查询所有用户 -->
<select id="selectAll" resultMap="BaseResultMap">
SELECT id, name, email, age, create_time
FROM t_user
ORDER BY id
</select>
<!-- 插入用户 -->
<insert id="insert" parameterType="com.example.entity.User"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO t_user (name, email, age, create_time)
VALUES (#{name}, #{email}, #{age}, NOW())
</insert>
<!--更新用户 -->
<update id="update" parameterType="com.example.entity.User">
UPDATE t_user
SET name = #{name},
email = #{email},
age = #{age}
WHERE id = #{id}
</update>
<!--删除用户 -->
<delete id="deleteById">
DELETE FROM t_user
WHERE id = #{id}
</delete>
<!--动态SQL查询 -->
<select id="selectByCondition" resultMap="BaseResultMap">
SELECT id, name, email, age, create_time
FROM t_user
<where>
<if test="name != null and name != ''">
AND name LIKE CONCAT('%', #{name}, '%')
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
ORDER BY id
</select>
</mapper>
| 元素 | 说明 | 示例 |
|---|---|---|
| select | 查询语句 | ... |
| insert | 插入语句 | ... |
| update | 更新语句 | ... |
| delete | 删除语句 | ... |
| resultMap | 结果映射 | ... |
| sql | 可重用的SQL片段 | ... |
| cache | 缓存配置 | |
| cache-ref | 引用缓存 |
3.2 注解配置方式
less
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<User> 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("<script>" +
"SELECT * FROM t_user " +
"<where>" +
"<if test='name != null'>" +
"AND name LIKE CONCAT('%', #{name}, '%')" +
"</if>" +
"<if test='age != null'>AND age = #{age}</if>" +
"</where>" +
"</script>")
List<User> selectByCondition(@Param("name") String name,
@Param("age") Integer age);
}
3.3 混合配置方式
XML和注解可以混合使用:
xml
public interface UserMapper {
//注解方式:简单查询
@Select("SELECT * FROM t_user WHERE id = #{id}")
User selectById(Long id);
//XML方式:复杂查询
List<User> selectByCondition(UserQuery query);
}
<mapper namespace="com.example.mapper.UserMapper">
<!-- 复杂查询使用XML -->
<select id="selectByCondition" resultMap="BaseResultMap">
SELECT * FROM t_user
<where>
<if test="name != null">
AND name LIKE CONCAT('%', #{name}, '%')
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
</mapper>
四、动态代理实现
MyBatis通过JDK动态代理自动实现Mapper接口。

4.1 MapperProxyFactory代理工厂
typescript
public class MapperProxyFactory<T> {
// Mapper接口类型
private final Class<T> mapperInterface;
// 方法缓存
private final Map<Method, MapperMethod> methodCache =
new ConcurrentHashMap<>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
//创建代理实例
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<>(
sqlSession, mapperInterface, methodCache
);
return newInstance(mapperProxy);
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
// 使用JDK动态代理创建代理对象
return (T) Proxy.newProxyInstance(
mapperInterface.getClassLoader(),
new Class[]{mapperInterface},
mapperProxy
);
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
}
4.2 MapperProxy代理类
kotlin
public class MapperProxy<T> implements InvocationHandler {
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface,
Map<Method, MapperMethod> 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 -> new MapperMethod(mapperInterface, method,
sqlSession.getConfiguration())
);
}
}
4.3 MapperMethod方法执行器
ini
public class MapperMethod {
// SqlCommand封装了SQL命令信息
private final SqlCommand command;
// MethodSignature封装了方法签名信息
private final MethodSignature method;
public MapperMethod(Class<?> 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() && 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() &&
(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 && method.getReturnType().isPrimitive() &&
!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 <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
List<E> 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 <K, V> Map<K, V> executeForMap(SqlSession sqlSession,
Object[] args) {
Object param = method.convertArgsToSqlCommandParam(args);
Map<K, V> 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 > 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<?> mapperInterface, Method method) {
final String methodName = method.getName();
final Class<?> 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<?> mapperInterface, String methodName,
Class<?> 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<?> returnType;
private final String mapKey;
private final Integer resultHandlerIndex;
private final Integer rowBoundsIndex;
private final ParamNameResolver paramNameResolver;
public MethodSignature(Configuration configuration,
Class<?> mapperInterface, Method method) {
Type resolvedReturnType = typeParameterResolver(method);
// 解析返回类型
if (resolvedReturnType instanceof Void) {
this.returnsVoid = true;
} else if (Collection.class.isAssignableFrom(
(Class<?>) resolvedReturnType) ||
resolvedReturnType.isArray()) {
this.returnsMany = true;
} else if (Map.class.isAssignableFrom(
(Class<?>) 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;
}
}
}
4.4 代理执行流程
markdown
1. 调用Mapper接口方法
↓
2. 触发MapperProxy.invoke()
↓
3. 获取或创建MapperMethod
↓
4. 执行MapperMethod.execute()
↓
5. 根据SQL类型调用SqlSession方法
↓
6. Executor执行SQL
↓
7. 返回结果
五、Mapper注册流程
Mapper接口需要注册到MyBatis才能使用。

5.1 注册方式
typescript
<configuration>
<!-- 注册Mapper接口 -->
<mappers>
<!--使用类路径 -->
<mapper class="com.example.mapper.UserMapper"/>
<!--使用包扫描 -->
<package name="com.example.mapper"/>
<!--使用XML资源路径 -->
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
// 创建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 <T> void addMapper(Class<T> type) {
mapperRegistry.addMapper(type);
}
// 获取Mapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
// 检查Mapper是否存在
public boolean hasMapper(Class<?> 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<BeanDefinitionHolder> doScan(String... basePackages) {
Set<BeanDefinitionHolder> 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<BeanDefinitionHolder> beanDefinitions) {
GenericBeanDefinition definition;
for (BeanDefinitionHolder holder : beanDefinitions) {
definition = (GenericBeanDefinition) holder.getBeanDefinition();
// 设置BeanClass为MapperFactoryBean
definition.getConstructorArgumentValues()
.addGenericArgumentValue(definition.getBeanClassName());
definition.setBeanClass(this.mapperFactoryBean.getClass());
// ... 省略其他配置
}
}
}
六、Mapper执行流程
理解Mapper的执行流程对于调试和优化至关重要。

6.1 完整执行流程
ini
//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();
}
6.2 详细执行步骤
css
步骤1: 获取Mapper代理对象
session.getMapper(UserMapper.class)
↓
configuration.getMapper(UserMapper.class, this)
↓
mapperRegistry.getMapper(UserMapper.class, this)
↓
mapperProxyFactory.newInstance(this)
↓
Proxy.newProxyInstance(...) → 创建代理对象
步骤2: 调用Mapper方法
userMapper.selectById(1L)
↓
MapperProxy.invoke(proxy, method, args)
↓
cachedMapperMethod(method)
↓
mapperMethod.execute(sqlSession, args)
步骤3: 执行SQL
SqlCommandType.SELECT
↓
sqlSession.selectOne(statementId, param)
↓
executor.query(ms, param, rowBounds, resultHandler)
↓
创建CacheKey
↓
查询缓存
↓
查询数据库
↓
映射结果
步骤4: 返回结果
处理ResultSet
↓
ObjectFactory创建对象
↓
ResultHandler映射
↓
返回User对象
6.3 执行时序图
应用 → MapperProxy → MapperMethod → SqlSession →
Executor → StatementHandler → Database
6.4 异常处理
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());
}
七、最佳实践
7.1 Mapper设计建议
css
1️⃣ 单一职责 - 每个Mapper对应一张表
2️⃣ 命名规范 - 接口名与实体名对应
3️⃣ 方法命名 - 使用语义化的方法名
4️⃣ 参数设计 - 使用@Param注解明确参数名
7.2 性能优化建议
1️⃣ 合理使用缓存 - 二级缓存提升性能
2️⃣ 避免N+1查询 - 使用关联查询
3️⃣ 分页查询 - 使用RowBounds或PageHelper
4️⃣ 批量操作 - 使用BatchExecutor
7.3 常见问题解决
sql
//错误:多参数未使用@Param
List<User> select(String name, Integer age);
//正确:使用@Param
List<User> select(@Param("name") String name,
@Param("age") Integer age);
<!--正确:使用resultMap -->
<resultMap id="BaseResultMap" type="User">
<id column="id" property="id"/>
<result column="user_name" property="name"/>
</resultMap>
<select id="selectById" resultMap="BaseResultMap">
SELECT id, user_name FROM t_user WHERE id = #{id}
</select>
八、总结
MyBatis的映射器模块通过接口+配置的方式,实现了优雅的数据库操作。
sql
1️⃣ Mapper接口 - 定义数据库操作方法
2️⃣ SQL映射 - XML或注解配置SQL语句
3️⃣ 动态代理 - JDK动态代理自动实现接口
4️⃣ MapperProxy - 拦截方法调用并执行SQL
5️⃣ MapperMethod - 封装方法执行逻辑