最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

MyBatis映射器模塊最佳實(shí)踐

 更新時(shí)間:2026年01月12日 11:30:27   作者:小馬不敲代碼  
MyBatis是一種優(yōu)秀的持久層框架,它通過(guò)接口+配置的方式實(shí)現(xiàn)了數(shù)據(jù)庫(kù)操作的優(yōu)雅,映射器模塊(MapperInterface)是用戶與MyBatis交互的主要入口,本文介紹MyBatis映射器模塊最佳實(shí)踐,感興趣的朋友跟隨小編一起看看吧

一、MyBatis整體架構(gòu)與映射器模塊

在深入映射器模塊之前,我們先了解MyBatis的整體架構(gòu),以及映射器模塊在其中的重要地位。

從架構(gòu)圖可以看出,MyBatis采用了分層架構(gòu)設(shè)計(jì),而映射器模塊(Mapper Interface)位于接口層,是用戶與MyBatis交互的主要入口。它通過(guò)接口定義數(shù)據(jù)庫(kù)操作,結(jié)合XML或注解配置SQL語(yǔ)句,利用動(dòng)態(tài)代理技術(shù)自動(dòng)實(shí)現(xiàn)接口,讓開(kāi)發(fā)者以面向?qū)ο蟮姆绞讲僮鲾?shù)據(jù)庫(kù)。

1.1 映射器模塊的核心職責(zé)

映射器模塊主要承擔(dān)以下核心職責(zé):
定義數(shù)據(jù)庫(kù)操作接口 - 通過(guò)Java接口定義CRUD操作
SQL語(yǔ)句映射 - 將接口方法與SQL語(yǔ)句關(guān)聯(lián)
參數(shù)映射 - 將方法參數(shù)轉(zhuǎn)換為SQL參數(shù)
結(jié)果映射 - 將查詢結(jié)果映射為Java對(duì)象
動(dòng)態(tài)代理實(shí)現(xiàn) - 自動(dòng)生成接口實(shí)現(xiàn)類

1.2 為什么需要Mapper?

傳統(tǒng)的JDBC編程存在以下問(wèn)題:

//傳統(tǒng)JDBC方式
String sql = "SELECT * FROM t_user WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();
// 手動(dòng)解析ResultSet并映射為對(duì)象...

這種方式的問(wèn)題:
1、SQL分散在代碼中,難以維護(hù)
2、參數(shù)設(shè)置和結(jié)果映射都是手工操作
3、容易出現(xiàn)類型轉(zhuǎn)換錯(cuò)誤
4、代碼重復(fù)度高

使用Mapper后:

//Mapper方式
@Select("SELECT * FROM t_user WHERE id = #{id}")
User selectById(Long id);
// 使用
User user = userMapper.selectById(1L);

優(yōu)勢(shì):
SQL與代碼分離,易于維護(hù)
自動(dòng)參數(shù)映射和結(jié)果映射
類型安全
代碼簡(jiǎn)潔

1.3 Mapper的使用方式

MyBatis支持兩種Mapper配置方式:

二、Mapper接口架構(gòu)

MyBatis的映射器模塊采用了接口+配置的設(shè)計(jì)模式。

2.1 Mapper接口定義

Mapper是一個(gè)普通的Java接口,無(wú)需實(shí)現(xiàn)類:

public interface UserMapper {
    // 查詢單個(gè)對(duì)象
    User selectById(Long id);
    // 查詢列表
    List<User> selectAll();
    // 插入
    int insert(User user);
    // 更新
    int update(User user);
    // 刪除
    int deleteById(Long id);
    // 復(fù)雜查詢
    List<User> selectByCondition(@Param("name") String name,
                                  @Param("age") Integer age);
}

2.2 Mapper接口特點(diǎn)

無(wú)需實(shí)現(xiàn)類 - MyBatis通過(guò)動(dòng)態(tài)代理自動(dòng)生成實(shí)現(xiàn)
方法名與SQL ID對(duì)應(yīng) - 接口方法名即為MappedStatement的ID
參數(shù)靈活 - 支持單參數(shù)、多參數(shù)、對(duì)象參數(shù)
返回值多樣 - 支持單對(duì)象、集合、Map等

2.3 MapperRegistry注冊(cè)中心

MyBatis維護(hù)了Mapper接口的注冊(cè)中心:

public class MapperRegistry {
    // Configuration對(duì)象
    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 {
                // 創(chuàng)建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實(shí)例
    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
            );
        }
    }
    // 檢查是否已注冊(cè)
    public <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }
    // 獲取所有Mapper接口
    public Collection<Class<?>> getMappers() {
        return Collections.unmodifiableCollection(knownMappers.keySet());
    }
}

三、SQL語(yǔ)句映射

MyBatis提供了靈活的SQL映射方式。

3.1 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">
    <!--結(jié)果映射 -->
    <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>
    <!--查詢單個(gè)用戶 -->
    <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>
    <!--動(dòng)態(tài)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>

3.2 注解配置方式

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和注解可以混合使用:

public interface UserMapper {
    //注解方式:簡(jiǎn)單查詢
    @Select("SELECT * FROM t_user WHERE id = #{id}")
    User selectById(Long id);
    //XML方式:復(fù)雜查詢
    List<User> selectByCondition(UserQuery query);
}
<mapper namespace="com.example.mapper.UserMapper">
    <!-- 復(fù)雜查詢使用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>

四、動(dòng)態(tài)代理實(shí)現(xiàn)

MyBatis通過(guò)JDK動(dòng)態(tài)代理自動(dòng)實(shí)現(xiàn)Mapper接口。

4.1 MapperProxyFactory代理工廠

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;
    }
    //創(chuàng)建代理實(shí)例
    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動(dòng)態(tài)代理創(chuàng)建代理對(duì)象
        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代理類

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類的方法,直接執(zhí)行
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {
                throw ExceptionUtil.unwrapThrowable(t);
            }
        }
        //2.獲取MapperMethod并執(zhí)行
        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方法執(zhí)行器

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 {
                    //返回單個(gè)對(duì)象
                    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;
    }
    // 執(zhí)行返回多條的查詢
    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;
    }
    // 執(zhí)行返回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;
    }
    // 處理行數(shù)結(jié)果
    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;
    }
    //內(nèi)部類: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;
        }
    }
    //內(nèi)部類: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 代理執(zhí)行流程

1. 調(diào)用Mapper接口方法
   ↓
2. 觸發(fā)MapperProxy.invoke()
   ↓
3. 獲取或創(chuàng)建MapperMethod
   ↓
4. 執(zhí)行MapperMethod.execute()
   ↓
5. 根據(jù)SQL類型調(diào)用SqlSession方法
   ↓
6. Executor執(zhí)行SQL
   ↓
7. 返回結(jié)果

五、Mapper注冊(cè)流程

Mapper接口需要注冊(cè)到MyBatis才能使用。

5.1 注冊(cè)方式

<configuration>
    <!-- 注冊(cè)Mapper接口 -->
    <mappers>
        <!--使用類路徑 -->
        <mapper class="com.example.mapper.UserMapper"/>
        <!--使用包掃描 -->
        <package name="com.example.mapper"/>
        <!--使用XML資源路徑 -->
        <mapper resource="com/example/mapper/UserMapper.xml"/>
    </mappers>
</configuration>
// 創(chuàng)建Configuration
Configuration configuration = new Configuration();
// 注冊(cè)Mapper接口
configuration.addMapper(UserMapper.class);
configuration.addMapper(OrderMapper.class);
// 或者通過(guò)MapperRegistry
MapperRegistry mapperRegistry = configuration.getMapperRegistry();
mapperRegistry.addMapper(UserMapper.class);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 通過(guò)InputStream
SqlSessionFactory factory = builder.build(inputStream);
// 通過(guò)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) {
        // 創(chuàng)建掃描器
        ClassPathMapperScanner scanner = 
            new ClassPathMapperScanner(registry);
        // 設(shè)置掃描包
        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();
            // 設(shè)置BeanClass為MapperFactoryBean
            definition.getConstructorArgumentValues()
                .addGenericArgumentValue(definition.getBeanClassName());
            definition.setBeanClass(this.mapperFactoryBean.getClass());
            // ... 省略其他配置
        }
    }
}

六、Mapper執(zhí)行流程

理解Mapper的執(zhí)行流程對(duì)于調(diào)試和優(yōu)化至關(guān)重要。

6.1 完整執(zhí)行流程

//1.獲取SqlSession
SqlSession session = sqlSessionFactory.openSession();
try {
    //2.獲取Mapper代理對(duì)象
    UserMapper userMapper = session.getMapper(UserMapper.class);
    //3.調(diào)用Mapper方法
    User user = userMapper.selectById(1L);
    //4.使用結(jié)果
    System.out.println(user);
    //5.提交事務(wù)
    session.commit();
} finally {
    //6.關(guān)閉Session
    session.close();
}

6.2 詳細(xì)執(zhí)行步驟

步驟1: 獲取Mapper代理對(duì)象

session.getMapper(UserMapper.class)
↓
configuration.getMapper(UserMapper.class, this)
↓
mapperRegistry.getMapper(UserMapper.class, this)
↓
mapperProxyFactory.newInstance(this)
↓
Proxy.newProxyInstance(...) → 創(chuàng)建代理對(duì)象

步驟2: 調(diào)用Mapper方法

   userMapper.selectById(1L)
    ↓
    MapperProxy.invoke(proxy, method, args)
    ↓
    cachedMapperMethod(method)
    ↓
    mapperMethod.execute(sqlSession, args)

步驟3: 執(zhí)行SQL

SqlCommandType.SELECT
↓
sqlSession.selectOne(statementId, param)
↓
executor.query(ms, param, rowBounds, resultHandler)
↓
創(chuàng)建CacheKey
↓
查詢緩存
↓
查詢數(shù)據(jù)庫(kù)
↓
映射結(jié)果

步驟4: 返回結(jié)果

 處理ResultSet
    ↓
    ObjectFactory創(chuàng)建對(duì)象
    ↓
    ResultHandler映射
    ↓
    返回User對(duì)象

6.3 執(zhí)行時(shí)序圖

應(yīng)用 → MapperProxy → MapperMethod → SqlSession → 
Executor → StatementHandler → Database

6.4 異常處理

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());
}

七、最佳實(shí)踐

7.1 Mapper設(shè)計(jì)建議

單一職責(zé) - 每個(gè)Mapper對(duì)應(yīng)一張表
命名規(guī)范 - 接口名與實(shí)體名對(duì)應(yīng)
方法命名 - 使用語(yǔ)義化的方法名
參數(shù)設(shè)計(jì) - 使用@Param注解明確參數(shù)名

7.2 性能優(yōu)化建議

合理使用緩存 - 二級(jí)緩存提升性能
避免N+1查詢 - 使用關(guān)聯(lián)查詢
分頁(yè)查詢 - 使用RowBounds或PageHelper
批量操作 - 使用BatchExecutor

7.3 常見(jiàn)問(wèn)題解決

//錯(cuò)誤:多參數(shù)未使用@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>

八、總結(jié)

MyBatis的映射器模塊通過(guò)接口+配置的方式,實(shí)現(xiàn)了優(yōu)雅的數(shù)據(jù)庫(kù)操作。
Mapper接口 - 定義數(shù)據(jù)庫(kù)操作方法
SQL映射 - XML或注解配置SQL語(yǔ)句
動(dòng)態(tài)代理 - JDK動(dòng)態(tài)代理自動(dòng)實(shí)現(xiàn)接口
MapperProxy - 攔截方法調(diào)用并執(zhí)行SQL
MapperMethod - 封裝方法執(zhí)行邏輯

到此這篇關(guān)于MyBatis映射器模塊最佳實(shí)踐的文章就介紹到這了,更多相關(guān)MyBatis映射器模塊內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

黎城县| 南乐县| 东安县| 巴南区| 晴隆县| 张家港市| 兴安盟| 绿春县| 绵竹市| 盐城市| 东丽区| 洞口县| 余干县| 洪雅县| 淮南市| 山阳县| 阿拉善左旗| 普定县| 临邑县| 龙里县| 六安市| 鞍山市| 南雄市| 乌兰察布市| 大港区| 松原市| 从江县| 潞西市| 文成县| 定边县| 江达县| 韩城市| 当雄县| 贵阳市| 武安市| 融水| 汽车| 全南县| 霍邱县| 肇东市| 峡江县|