傳統方式:sqlSession.selectOne("namespace.id", param),字符串硬編碼、重構困難。接口式開發:定義接口,MyBatis 自動生成代理實現,編譯期檢查、IDE 跳轉、重構友好。
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>
SqlSession sqlSession = sqlSessionFactory.openSession(); IMessageOperation mapper = sqlSession.getMapper(IMessageOperation.class); Message msg = mapper.selectMessageById(3); // 類型安全調用 sqlSession.close();
getMapper() 內部使用 MapperProxyFactory 創建 MapperProxy(JDK 動態代理),攔截方法調用 → 解析 MappedStatement → 執行 SQL → 映射結果返回。
MapperScannerConfigurer 掃描註冊。