Mybatis原始碼研究之BoundSql
阿新 • • 發佈:2019-02-13
Mybatis裡難得有註釋的類
BoundSql
, 而且此註釋出現在 3.3.1+ 版本, 在3.2.2時都還沒有.
1. 概述
BoundSql
更像一箇中轉站, Mybatis在執行一次CRUD操作過程中產生的中間資料的集中點.這一點觀察其內部的欄位就可以瞭解.- 內部基本沒做什麼處理, 只是將相應的操作排程給了內部的欄位.
2. 註釋
/**
* An actual SQL String got form an {@link SqlSource} after having processed any dynamic content.
* The SQL may have SQL placeholders "?" and an list (ordered) of an parameter mappings
* with the additional information for each parameter (at least the property name of the input object to read
* the value from).
* </br>
* Can also have additional parameters that are created by the dynamic language (for loops, bind...).
*/
// 其中包含sql語句(該sql語句中可能包含 ? 這樣的佔位符), 以及一組parameter mapping(ParameterMapping類的例項), 注意這組parameter mapping是Mybatis內部生成的(通過讀取#{xx}中的內容)
// 再強調一次,以上的ParameterMapping例項是在ParameterHandler介面的唯一預設實現類 DefaultParameterHandler 中被消費的.
3. 全域性類欄位
// 進行 #{ } 和 ${ } 替換完畢之後的結果sql, 注意每個 #{ }替換完之後就是一個 ?
private String sql;
// 這裡的parameterMappings列表引數裡的item個數, 以及每個item的屬性名稱等等, 都是和上面的sql中的 ? 完全一一對應的.
private List<ParameterMapping> parameterMappings;
// 使用者傳入的資料
private Object parameterObject;
private Map<String, Object> additionalParameters;
private MetaObject metaParameters;
4. 建構函式
public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
//sql : SELECT us_code FROM xxx WHERE us_code = ? AND us_keyid IS NOT NULL
// 到達這裡的sql(即用來構建BoundSql例項的sql), 是進行 #{ } 和 ${ } 替換完畢之後的結果sql
this.sql = sql;
//parameterMappings : [ParameterMapping{property='username', mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}]
// 這裡的parameterMappings列表引數裡的item個數, 以及每個item的屬性名稱等等, 都是和上面的sql中的 ? 完全一一對應的.
this.parameterMappings = parameterMappings;
// parameterObject : 使用者傳入的資料
this.parameterObject = parameterObject;
this.additionalParameters = new HashMap<String, Object>();
this.metaParameters = configuration.newMetaObject(this.additionalParameters);
}
//------------------- 對應的對映語句
SELECT
us_code
FROM
xxx
WHERE
us_code = #{username}
AND us_keyid IS NOT NULL
5. SqlSource
注意
SqlSource
介面中的唯一方法getBoundSql
,其返回值就是BoundSql
.