MyBatis作爲Java火熱的框架,如果去面試的話,一定會被問到,所以這裏總結MyBatis常見的面試題。
下面的面試題中有關代碼的地方都是圍繞這四張表來說。
- 用戶表與身份證表是一對一關係,也就是一個用戶只能擁有一個身份證,而一個身份證只能屬於一個用戶。
- 用戶表與角色表是多對多關係,多對多關係是雙向的一對多關係,也就是一個用戶可以擁有多個角色,而一個角色也可以屬於多個用戶。多對多關係通過中間表來關聯。中間表一般只有兩個字段,設置爲聯合主鍵,並且都是外鍵分別指向兩張表的主鍵。
建表SQL語句
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用戶ID',
`user_name` varchar(50) DEFAULT NULL COMMENT '用戶名',
`user_password` varchar(50) DEFAULT NULL COMMENT '密碼',
`user_email` varchar(255) DEFAULT '[email protected]' COMMENT '郵箱',
`user_info` text COMMENT '簡介',
`head_img` blob COMMENT '頭像',
`create_time` datetime DEFAULT NULL COMMENT '創建時間',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COMMENT='用戶表';
CREATE TABLE `sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
`role_name` varchar(50) DEFAULT NULL COMMENT '角色名',
`enabled` int(11) DEFAULT NULL COMMENT '有效標誌',
`create_by` bigint(20) DEFAULT NULL COMMENT '創建人',
`create_time` datetime DEFAULT NULL COMMENT '創建時間',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='角色表';
CREATE TABLE `sys_user_role` (
`user_id` bigint(20) NOT NULL COMMENT '用戶ID',
`role_id` bigint(20) NOT NULL COMMENT '角色ID',
PRIMARY KEY (`user_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用戶角色關聯表';
CREATE TABLE `id_card` (
`id` bigint(32) NOT NULL AUTO_INCREMENT,
`id_number` varchar(32) DEFAULT NULL,
`user_id` bigint(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='身份證表';
一般有表就要有實體類,這裏就不貼實體類的代碼,實體類中的屬性都是駝峯命名法,而表字段都是下劃線命名法。
1.什麼是MyBatis?
- Mybatis 是一個半 ORM(對象關係映射)框架,它內部封裝了 JDBC,開發時只需要關注 SQL 語句本身,不需要花費精力去處理加載驅動、創建連接、創建statement 等繁雜的過程。程序員直接編寫原生態 sql,可以嚴格控制 sql 執行性能,靈活度高。
- MyBatis 可以使用 XML 或註解來配置和映射原生信息,將 POJO 映射成數據庫中的記錄,避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。
- 通過 xml 文件或註解的方式將要執行的各種 statement 配置起來,並通過java 對象和 statement 中 sql 的動態參數進行映射生成最終執行的 sql 語句,最後由 mybatis 框架執行 sql 並將結果映射爲 java 對象並返回。(從執行 sql 到返回 result 的過程)。
2.MyBatis的優點
- 基於 SQL 語句編程,相當靈活,不會對應用程序或者數據庫的現有設計造成任何影響,SQL 寫在 XML 裏,解除 sql 與程序代碼的耦合,便於統一管理;提供 XML標籤,支持編寫動態 SQL 語句,並可重用。
- 與 JDBC 相比,減少了大量代碼量,消除了 JDBC 大量冗餘的代碼,不需要手動開關連接;
- 很好的與各種數據庫兼容(因爲 MyBatis 使用 JDBC 來連接數據庫,所以只要JDBC 支持的數據庫 MyBatis 都支持)。
- 能夠與 Spring 很好的集成;
- 提供映射標籤,支持對象與數據庫的 ORM 字段關係映射;提供對象關係映射標籤,支持對象關係組件維護。
3.MyBatis的缺點
- SQL 語句的編寫工作量較大,尤其當字段多、關聯表多時,對開發人員編寫SQL 語句的功底有一定要求。
- SQL 語句依賴於數據庫,導致數據庫移植性差,不能隨意更換數據庫。
4.MyBatis適用場合
- MyBatis 專注於 SQL 本身,是一個足夠靈活的 DAO 層解決方案。
- 對性能的要求很高,或者需求變化較多的項目,如互聯網項目,MyBatis 將是不錯的選擇。
5.MyBatis與Hibernate有哪些不同?
- Mybatis 和 hibernate 不同,它不完全是一個 ORM 框架,因爲 MyBatis 需要程序員自己編寫 Sql 語句。
- Mybatis 直接編寫原生態 sql,可以嚴格控制 sql 執行性能,靈活度高,非常適合對關係數據模型要求不高的軟件開發,因爲這類軟件需求變化頻繁,一但需求變化要求迅速輸出成果。但是靈活的前提是mybatis無法做到數據庫無關性,如果需要實現支持多種數據庫的軟件,則需要自定義多套 sql 映射文件,工作量大。
- Hibernate 對象/關係映射能力強,數據庫無關性好,對於關係模型要求高的軟件,如果用 hibernate 開發可以節省很多代碼,提高效率。
6.#{}和${}的區別是什麼?
#{}
是預編譯處理,${}
是字符串替換。- Mybatis在處理
#{
}時,會將sql中的#{}
替換爲?號,調用PreparedStatement的set方法來賦值; - Mybatis在處理
${}
時,就是把${}
替換成變量的值。 - 使用
#{}
可以有效的防止SQL注入,提高系統安全性。
7.當實體類中的屬性名和表中的字段名不一樣 ,怎麼辦 ?
- 第1種,通過在查詢的 sql 語句中定義字段名的別名,讓字段名的別名和實體類的屬性名一致。
<select id="selectUserByUid" resultType="SysUser">
select
id,
user_name userName,
user_password userPassword,
user_email userEmail,
user_info userInfo,
head_img headImg,
create_time CreateTime
from sys_user
where id = #{id}
</select>
- 第2種,通過<resultMap>來映射字段名和實體類屬性名的一 一對應的關係。
<resultMap id="userMap" type="cn.zwq.mybatis.model.SysUser">
<id property="id" column="id"/>
<result property="userName" column="user_name"/>
<result property="userPassword" column="user_password"/>
<result property="userEmail" column="user_email"/>
<result property="userInfo" column="user_info"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="headImg" column="head_img" jdbcType="BLOB"/>
</resultMap>
8.模糊查詢like語句該怎麼寫?
- 在Java代碼中添加sql通配符。
string userName= “%zs%”;
list<SysUser> sysUsers= sysUserMapper.selectlike(userName);
<select id=”selectlike”>
select * from sys_user where userName like #{value}
</select>
- 在sql語句中拼接通配符,會引起sql注入。
string userName= “zs”;
list<SysUser> sysUsers= sysUserMapper.selectlike(userName);
<select id=”selectlike”>
select * from sys_user where userName like "%"#{value}"%"
</select>
- 使用bind動態標籤拼接通配符,不會引起sql注入。
string userName= “zs”;
list<SysUser> sysUsers= sysUserMapper.selectlike(userName);
<select id=”selectlike”>
<bind name="userName" value="'%'+userName+'%'"/>
select * from sys_user where userName like #{userName}
</select>
9.XML映射文件對應一個Mapper接口,請問,這個Mapper接口的工作原理是什麼?
- Mapper接口的全限名,就是 Mapper.xml 中的 namespace 的值;接口的方法名,就是 Mapper.xml 中的 Statement 的 id 值;接口方法內的參數,就是傳遞給 sql 的參數。
- Mapper 接口是沒有實現類的,當調用接口方法時,接口全限名+方法名拼接字符串作爲 key 值,可唯一定位一個MapperStatement。在 Mybatis 中,每一個<select>、<insert>、<update>、<delete> 標籤,都會被解析爲一個MapperStatement 對象。
舉例:cn.zwq.mybatis.mapper.SysUserMapper.findSysUserById ,可以唯一找到 namespace 爲 cn.zwq.mybatis.mapper.SysUserMapper 下面 id 爲 findSysUserById 的 MapperStatement。
10.Mapper接口裏的方法,參數不同時,方法能重載嗎?
- Mapper 接口裏的方法可以重載的,但是Mapper.xml中的statement id是不允許重複的。
- 因爲是使用 全限名+方法名 的保存和尋找策略。Mapper 接口的工作原理是 JDK 動態代理,Mybatis 運行時會使用 JDK動態代理爲 Mapper 接口生成代理對象 proxy,代理對象會攔截接口方法,轉而執行 MapperStatement 所代表的 sql,然後將 sql 執行結果返回。
11.Mybatis是如何進行分頁的?分頁插件的原理是什麼?
- Mybatis 使用 RowBounds 對象進行分頁,它是針對 ResultSet 結果集執行的內存分頁,而非物理分頁。可以在 sql 內直接書寫帶有物理分頁的參數來完成物理分頁功能,也可以使用分頁插件來完成物理分頁。
- 分頁插件的基本原理是使用 Mybatis 提供的插件接口,實現自定義插件,在插件的攔截方法內攔截待執行的 sql,然後重寫sql,根據 dialect 方言,添加對應的物理分頁語句和物理分頁參數。
12.Mybatis是如何將sql執行結果封裝爲目標對象並返回的?都有哪些映射形式?
- 使用<resultMap>標籤,逐一定義數據庫列名和對象屬性名之間的映射關係。
<resultMap id="userMap" type="cn.zwq.mybatis.model.SysUser">
<id property="id" column="id"/>
<result property="userName" column="user_name"/>
<result property="userPassword" column="user_password"/>
<result property="userEmail" column="user_email"/>
<result property="userInfo" column="user_info"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="headImg" column="head_img" jdbcType="BLOB"/>
</resultMap>
- 使用 sql 列的別名功能,將列的別名書寫爲對象屬性名。有了列名與屬性名的映射關係後,Mybatis 通過反射創建對象,同時使用反射給對象的屬性逐一賦值並返回,那些找不到映射關係的屬性,是無法完成賦值的。
<select id="selectUserByUid" resultType="SysUser">
select
id,
user_name userName,
user_password userPassword,
user_email userEmail,
user_info userInfo,
head_img headImg,
create_time CreateTime
from sys_user
where id = #{id}
</select>
13.如何執行批量插入?
- 使用MyBatis foreach動態sql
/**
* 批量插入用戶數據
* @param users
* @return
*/
int insertBatch(List<SysUser> users);
<insert id="insertBatch" useGeneratedKeys="true" keyProperty="id">
insert into sys_user(
user_name,
user_password,
user_email,
user_info,
head_img,
create_time)
values
<foreach collection="list" item="user" separator=",">
(
#{user.userName},
#{user.userPassword},
#{user.userEmail},
#{user.userInfo},
#{user.headImg,jdbcType=BLOB},
#{user.createTime,jdbcType=TIMESTAMP}
)
</foreach>
</insert>
- 使用Java代碼
14.如何獲取自動生成的主鍵值?
這個答案看這篇博客更加詳細
https://blog.csdn.net/weixin_44176169/article/details/104716942
15.Mapper接口方法如何傳遞多個參數?
/**
* 根據用戶id和角色的enabled狀態來查詢用戶的所有角色
* @param id
* @param enabled
* @return
*/
List<SysRole> selectSysRolesByUidAndEnabled(Long id,Integer enabled);
對於上面的接口中有兩個參數,我們有三種方式可以在sql語句中獲取到它們
- MyBatis默認會爲每個參數定義爲:arg0或param0,arg1或param1,…,也就是我們使用#{arg0}或#{param0}就能獲取到參數
- 使用MyBatis中的@Param註解,改造接口如下,這樣我們就能使用註解中指定的名稱獲取參數:#{id},#{enabled}
/**
* 根據用戶id和角色的enabled狀態來查詢用戶的所有角色
* @param id
* @param enabled
* @return
*/
List<SysRole> selectSysRolesByUidAndEnabled(@Param("id") Long id, @Param("enabled") Integer enabled);
- 使用Map集合封裝多個參數,就是將每個參數的名稱作爲key,值作爲value,改造接口如下
/**
* 根據用戶id和角色的enabled狀態來查詢用戶的所有角色
* @param id
* @param enabled
* @return
*/
List<SysRole> selectSysRolesByUidAndEnabled(Map<String,Object> map);
16.Mybatis動態sql有什麼用?執行原理?有哪些動態sql?
- MyBatis的動態sql可以寫在Mapper.xml內,以標籤的形式編寫動態sql,執行原理是根據表達式的值完成邏輯判斷並動態拼接sql。
- Mybatis 提供了 9 種動態 sql 標籤:
trim | where | set | foreach | if | choose| when | otherwise | bind 。
17.Mapper.xml除了常見的select|insert|updae|delete標籤之外,還有哪些標籤?
- <resultMap>、<parameterMap>、<sql>、<include>、<selectKey>,加上動態 sql 的 9 個標籤,
- 其中 <sql> 爲 sql 片段標籤,通過<include> 標籤引入 sql 片段, <selectKey> 爲不支持自增的主鍵生成策略標籤。
18.MyBatis的XML映射文件中,不同的XML映射文件,id是否可以重複?
- 不同的 XML 映射文件,如果配置了 namespace,那麼 id 可以重複;如果沒有配置 namespace,那麼 id 不能重複。
- 原因就是 namespace+id 是作爲Map <String, MapperStatement>的 key使用的,如果沒有 namespace,就剩下 id,那麼,id 重複會導致數據互相覆蓋。有了 namespace,自然 id 就可以重複,namespace 不同,namespace+id 自然也就不同。
19.爲什麼說MyBatis是半自動ORM映射框架?它與全自動的區別在哪裏?
- Hibernate 屬於全自動 ORM 映射框架,使用 Hibernate 查詢關聯對象或者關聯集合對象時,可以根據對象關係模型直接獲取,所以它是全自動的。
- Mybatis在查詢關聯對象或關聯集合對象時,需要手動編寫 sql 來完成,所以,稱之爲半自動 ORM 映射框架。
20.MyBatis實現一對一有幾種方式?具體怎麼操作的?
- 有聯合查詢和嵌套查詢兩種方式。
- 聯合查詢是幾個表聯合查詢,只查詢一次, 通過在<resultMap>標籤裏面配置<association>標籤配置一對一的類就可以完成。
SysUserMapper接口
SysUser selectUserAndIdCardByUid(Long uid);
SysUserMapper.xml
<resultMap id="userMap" type="cn.zwq.mybatis.model.SysUser">
<id property="id" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="userPassword" column="user_password"/>
<result property="userEmail" column="user_email"/>
<result property="userInfo" column="user_info"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="headImg" column="head_img" jdbcType="BLOB"/>
</resultMap>
<resultMap id="userIdCardMap" type="SysUser" extends="userMap">
<association property="idCard" columnPrefix="card_" resultMap="cn.zwq.mybatis.mapper.IdCardMapper.idCardMap"/>
</resultMap>
<select id="selectUserAndIdCardByUid" resultMap="userIdCardMap">
select
u.id,
u.user_name,
u.user_password,
u.user_email,
u.user_info,
u.head_img,
u.create_time,
c.id card_id,
c.id_number crad_id_number,
c.user_id card_user_id
from sys_user u inner join id_card c on u.id = c.user_id
where u.id = #{id}
</select>
IdCardMapper.xml
<resultMap id="idCardMap" type="cn.zwq.mybatis.model.IdCard">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="in_number" jdbcType="VARCHAR" property="idNumber" />
<result column="user_id" jdbcType="BIGINT" property="userId" />
</resultMap>
- 嵌套查詢是先查一個表,根據這個表裏面的結果的外鍵 id,再去另外一個表裏面查詢數據,也是通過<association>標籤配置,但另外一個表的查詢通過<association>標籤的select屬性配置。
SysUserMapper接口
SysUser selectUserAndIdCardByUid(Long uid);
SysUserMapper.xml
<resultMap id="userMap" type="cn.zwq.mybatis.model.SysUser">
<id property="id" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="userPassword" column="user_password"/>
<result property="userEmail" column="user_email"/>
<result property="userInfo" column="user_info"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="headImg" column="head_img" jdbcType="BLOB"/>
</resultMap>
<resultMap id="userIdCardMap" type="SysUser" extends="userMap">
<association property="idCard"
select="cn.zwq.mybatis.mapper.IdCardMapper.selectIdCardById"
column="{id=id}"
fetchType="lazy"/>
</resultMap>
<select id="selectUserAndIdCardByUid" resultMap="userIdCardMap">
select
u.id,
u.user_name,
u.user_password,
u.user_email,
u.user_info,
u.head_img,
u.create_time
from sys_user u
where id = #{id}
</select>
IdCardMapper.xml
<resultMap id="idCardMap" type="cn.zwq.mybatis.model.IdCard">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="id_number" jdbcType="VARCHAR" property="idNumber" />
<result column="user_id" jdbcType="BIGINT" property="userId" />
</resultMap>
<select id="selectIdCardById" resultMap="idCardMap">
select * from id_card where user_id = #{id}
</select>
21.MyBatis實現一對多有幾種方式,具體怎麼操作的?
- 有聯合查詢和嵌套查詢兩種方式。
- 聯合查詢是幾個表聯合查詢,只查詢一次,通過在<resultMap>標籤裏面的<collection>標籤配置一對多的類就可以完成。
SysUserMapper接口
SysUser selectSysUserAndSysRolesByUid(Long id);
SysUserMapper.xml
<resultMap id="userMap" type="cn.zwq.mybatis.model.SysUser">
<id property="id" column="id"/>
<result property="userName" column="user_name"/>
<result property="userPassword" column="user_password"/>
<result property="userEmail" column="user_email"/>
<result property="userInfo" column="user_info"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="headImg" column="head_img" jdbcType="BLOB"/>
</resultMap>
<resultMap id="userRoleMap" type="SysUser" extends="userMap">
<!--role集合對象-->
<collection property="roles" columnPrefix="role_"
resultMap="cn.zwq.mybatis.mapper.SysRoleMapper.roleMap"/>
</resultMap>
<select id="selectSysUserAndSysRolesByUid" resultMap="userRoleMap">
select
u.id id,
user_name,
user_password,
user_email,
user_info,
head_img,
u.create_time,
r.id role_id,
r.role_name role_role_name,
r.enabled role_enabled,
r.create_by role_create_by,
r.create_time role_create_time
from sys_user u inner join sys_user_role ur on u.id = ur.user_id
inner join sys_role r on r.id = ur.role_id where u.id = #{id};
</select>
SysRoleMapper.xml
<resultMap id="roleMap" type="cn.zwq.mybatis.model.SysRole">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="role_name" jdbcType="VARCHAR" property="roleName" />
<result column="enabled" jdbcType="INTEGER" property="enabled" />
<result column="create_by" jdbcType="BIGINT" property="createBy" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap>
- 嵌套查詢是先查一個表,根據這個表裏面的結果的外鍵id,再去另外一個表裏面查詢數據,也是通過配置<collection>,但另外一個表的查詢通過<collection>標籤的select屬性配置。
SysUserMapper接口
SysUser selectSysUserAndSysRolesByUid(Long id);
SysUserMapper.xml
<resultMap id="userMap" type="cn.zwq.mybatis.model.SysUser">
<id property="id" column="id"/>
<result property="userName" column="user_name"/>
<result property="userPassword" column="user_password"/>
<result property="userEmail" column="user_email"/>
<result property="userInfo" column="user_info"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="headImg" column="head_img" jdbcType="BLOB"/>
</resultMap>
<resultMap id="userRoleMap" type="SysUser" extends="userMap">
<!--role集合對象-->
<collection property="roles"
select="cn.zwq.mybatis.mapper.SysRoleMapper.selectByUserId"
column="{id=id}"
fetchType="lazy"/>
</resultMap>
<select id="selectSysUserAndSysRolesByUid" resultMap="userRoleMap">
select
u.id id,
u.user_name,
u.user_password,
u.user_email,
u.user_info,
u.head_img,
u.create_time
from sys_user u
where u.id = #{id};
</select>
SysRoleMapper.xml
<resultMap id="roleMap" type="cn.zwq.mybatis.model.SysRole">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="role_name" jdbcType="VARCHAR" property="roleName" />
<result column="enabled" jdbcType="INTEGER" property="enabled" />
<result column="create_by" jdbcType="BIGINT" property="createBy" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap>
<select id="selectByUserId" resultMap="roleMap">
select id, role_name, enabled, create_by, create_time
from sys_role r inner join sys_user_role ur on ur.role_id = r.id
where ur.user_id = #{id,jdbcType=BIGINT}
</select>
22.MyBatis是否支持延遲加載?如果支持,它的實現原理是什麼?
- Mybatis僅支持association關聯對象和collection關聯集合對象的延遲加載,association指的就是一對一,collection指的就是一對多查詢。
- lazyLoadingEnabled:延遲加載的全局開關。當開啓時,所有關聯對象都會延遲加載。
- aggressiveLazyLoading:當開啓時,任何方法的調用都會加載該對象的所有屬性。否則,每個屬性會按需加載(參考lazyLoadTriggerMethods)。
- lazyLoadTriggerMethods:指定哪個對象的方法觸發一次延遲加載。用逗號分隔的方法列表,默認執行下面方法就觸發延遲加載:equals,clone,hashCode,toString。
- fetchType:爲每一次查詢決定是否延遲加載,可以覆蓋lazyLoadingEnabled配置。lazy:延遲加載;eager:積極加載。
23.MyBatis的一級、二級緩存
- 一級緩存: 基於 PerpetualCache 的 HashMap 本地緩存,其存儲作用域爲SqlSession,當 SqlSession flush 或 close 之後,該 SqlSession 中的所有 Cache 就將清空,默認打開一級緩存。
- 二級緩存與一級緩存其機制相同,默認也是採用 PerpetualCache,HashMap存儲,不同在於其存儲作用域爲 Mapper(Namespace),並且可自定義存儲源,如 Ehcache。默認不打開二級緩存,要開啓二級緩存,使用二級緩存屬性類需要實現 Serializable 序列化接口(可用來保存對象的狀態),可在它的映射文件中配置<cache/>
- 對於緩存數據更新機制,當某一個作用域(一級緩存 SqlSession,二級緩存Namespaces)的進行了CUD操作後,默認該作用域下所有select 中的緩存將被 clear。
24.什麼是MyBatis的接口綁定?有哪些實現方式?
- 接口綁定,就是在 MyBatis 中任意定義接口,然後把接口裏面的方法和 SQL 語句綁定, 我們直接調用接口方法就可以,這樣比起原來了 SqlSession 提供的方法我們可以有更加靈活的選擇和設置。
- 接口綁定有兩種實現方式,一種是通過註解綁定,就是在接口的方法上面加上@Select、@Update 等註解,裏面包含 Sql 語句來綁定。
- 另外一種就是通過 xml裏面寫 SQL 來綁定, 在這種情況下,要指定 xml 映射文件裏面的 namespace 必須爲接口的全路徑名。當 Sql 語句比較簡單時候,用註解綁定, 當 SQL 語句比較複雜時候,用 xml 綁定,一般用 xml 綁定的比較多。
25.使用MyBatis的Mapper接口調用時有哪些要求?
- Mapper 接口方法名和 Mapper.xml 中定義的每個 sql 的 id 相同;
- Mapper 接口方法的輸入參數類型和 Mapper.xml 中定義的每個 sql 的parameterType 的類型相同;
- Mapper 接口方法的輸出參數類型和 mapper.xml 中定義的每個 sql 的resultType 的類型相同;
- Mapper.xml 文件中的 namespace 即是 mapper 接口的類路徑。
26.簡述MyBatis的插件運行原理,以及如何編寫一個插件
- Mybatis 僅可以編寫針對 ParameterHandler、ResultSetHandler、StatementHandler、Executor 這 4 種接口的插件,Mybatis 使用 JDK 的動態代理,爲需要攔截的接口生成代理對象以實現接口方法攔截功能,每當執行這 4 種接口對象的方法時,就會進入攔截方法,具體就是 InvocationHandler 的 invoke()方法,當然,只會攔截那些你指定需要攔截的方法。
- 編寫插件:實現 Mybatis 的 Interceptor 接口並複寫 intercept()方法,然後在給插件編寫註解,指定要攔截哪一個接口的哪些方法即可,最後,需要在配置文件中配置你編寫的插件。