首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

MyBatis 接口式開發實戰(二):Mapper 動態代理最佳實踐

     編輯:Java 綜合教學

MyBatis 接口式開發實戰(二):Mapper 動態代理最佳實踐

從 XML 命名空間到接口綁定

傳統方式:sqlSession.selectOne("namespace.id", param),字符串硬編碼、重構困難。接口式開發:定義接口,MyBatis 自動生成代理實現,編譯期檢查、IDE 跳轉、重構友好。

1. 映射文件與接口對應規範

  • Mapper XML namespace = 接口全限定名。
  • <select id="selectUserByID" ...> 的 id = 接口方法名。
  • 參數類型、返回類型與 parameterType/resultType 一致。
// 接口
package com.cn.inter;
public interface IMessageOperation {
    Message selectMessageById(Integer id);
}

// XML
<mapper namespace="com.cn.inter.IMessageOperation">
    <select id="selectMessageById" parameterType="int" resultType="Message">
        select * from message where id = #{id}
    </select>
</mapper>

2. 代碼獲取代理並調用

SqlSession sqlSession = sqlSessionFactory.openSession();
IMessageOperation mapper = sqlSession.getMapper(IMessageOperation.class);
Message msg = mapper.selectMessageById(3);  // 類型安全調用
sqlSession.close();

3. 底層原理

getMapper() 內部使用 MapperProxyFactory 創建 MapperProxy(JDK 動態代理),攔截方法調用 → 解析 MappedStatement → 執行 SQL → 映射結果返回。

4. 優勢總結

  • 消除魔法字符串,重構安全。
  • 接口即契約,實現解耦。
  • 支持多方法、默認方法(JDK 8+)、泛型方法。
  • 易於單元測試(Mock 接口)。

5. 注意事項

  • 接口方法不可重載(MyBatis 無法區分)。
  • Mapper 接口不要定義為 Spring Bean(由 MyBatis 管理代理),Spring 整合時用 MapperScannerConfigurer 掃描註冊。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved