通過 mapper 接口加載映射檔案,這對于後面 ssm三大架構 的整合是非常重要的。那麼什麼是通過 mapper 接口加載映射檔案呢?
我們首先看以前的做法,在全局配置檔案 mybatis-configuration.xml 通過 <mappers> 标簽來加載映射檔案,那麼如果我們項目足夠大,有很多映射檔案呢,難道我們每一個映射檔案都這樣加載嗎,這樣肯定是不行的,那麼我們就需要使用 mapper 接口來加載映射檔案
以前的做法:

1、定義 userMapper 接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
2、在全局配置檔案 mybatis-configuration.xml 檔案中加載 UserMapper 接口(單個加載映射檔案)
3、編寫UserMapper.xml 檔案
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
4、測試
|
5、批量加載映射檔案
|
6、注意
1、UserMapper 接口必須要和 UserMapper.xml 檔案同名且在同一個包下,也就是說 UserMapper.xml 檔案中的namespace是UserMapper接口的全類名
2、UserMapper接口中的方法名和 UserMapper.xml 檔案中定義的 id 一緻
3、UserMapper接口輸入參數類型要和 UserMapper.xml 中定義的 parameterType 一緻
4、UserMapper接口傳回資料類型要和 UserMapper.xml 中定義的 resultType 一緻