前言
Mybatis參數(shù)處理是Mybatis核心內(nèi)容福侈,圍繞著Mybatis的面試題也是層出不窮。接下來(lái)跟隨源碼看下Mybatis是如何處理參數(shù)的浓领。
代碼示例
Mapper
ApplicationEntity getByCode(@Param("code") String code);
XML
<select id="getByCode" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM application
WHERE code =#{code} AND deleted =0
</select>
JunitTest
@ActiveProfiles("dev")
@SpringBootTest
@RunWith(SpringRunner.class)
public class MybatisTest {
//這里注入的實(shí)際上是一個(gè)代理類
@Autowired
private ApplicationMapper applicationMapper;
@Test
public void testMybatis(){
ApplicationEntity applicationEntity = applicationMapper.getByCode("w1111");
System.out.println(applicationEntity);
}
}
- 這里注入的實(shí)際上是一個(gè)代理類犯戏,這個(gè)代理類是在應(yīng)用啟動(dòng)的時(shí)候spring發(fā)現(xiàn)其他bean注入了這個(gè)類,就通過(guò)BeanFactory.getBean()娘汞,再通過(guò)FactoryBean(MapperFactoryBean).getObject()歹茶,最后通過(guò)動(dòng)態(tài)代理注入得到。Mybatis參數(shù)處理
idea debug進(jìn)入下一步你弦,可以發(fā)現(xiàn)進(jìn)入了MapperProxy的invoke方法惊豺。
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//這里的method.getDeclaringClass()的值是com.xt.algorithm.mapper.LoanApplicationMapper
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
//isDefaultMethod(method)返回false
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
//將MapperMethod緩存起來(lái)
final MapperMethod mapperMethod = cachedMapperMethod(method);
//最后執(zhí)行mapperMethos.execute()方法
return mapperMethod.execute(sqlSession, args);
}
private MapperMethod cachedMapperMethod(Method method) {
return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
接下來(lái)看下MapperMethod.execute()方法是如何處理參數(shù)的。
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional() &&
(result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
//...
return result;
}
可以看到對(duì)于參數(shù)處理禽作,都是通過(guò)Object param = method.convertArgsToSqlCommandParam(args);去處理的尸昧,那么我們看下這個(gè)方法到底做了什么操作。
public Object convertArgsToSqlCommandParam(Object[] args) {
return paramNameResolver.getNamedParams(args);
}
public Object getNamedParams(Object[] args) {
final int paramCount = names.size();
if (args == null || paramCount == 0) {
//如果沒(méi)有入?yún)⒖醭ィ蛘叻椒ǘx參數(shù)個(gè)數(shù)為0烹俗,直接返回null
return null;
} else if (!hasParamAnnotation && paramCount == 1) {
//如果沒(méi)有使用@Param注解碍沐,且參數(shù)個(gè)數(shù)為1個(gè),直接返回入?yún)? return args[names.firstKey()];
} else {
//否則衷蜓,遍歷方法names
final Map<String, Object> param = new ParamMap<>();
int i = 0;
for (Map.Entry<Integer, String> entry : names.entrySet()) {
//這里將names的鍵值對(duì)放入param中
param.put(entry.getValue(), args[entry.getKey()]);
// add generic param names (param1, param2, ...)
//并添加{"param1":entay.getKey()}形式放入param中
final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
// ensure not to overwrite parameter named with @Param
if (!names.containsValue(genericParamName)) {
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}
可以看到ParamNameResolver.getNamedParams()方法的入?yún)rgs就是mapper接口上方法值累提。
names是一個(gè)SortedMap,內(nèi)部的鍵值對(duì)磁浇,key為參數(shù)在接口方法中的索引位置(方法入?yún)⒅械牡趲讉€(gè)參數(shù)斋陪,從0開(kāi)始),value為@Param的value值(如果沒(méi)有使用@Param注解置吓,默認(rèn)為arg0,arg1...)无虚。
這一部分可從ParamNameResolver的構(gòu)造函數(shù)中看出。
public ParamNameResolver(Configuration config, Method method) {
//獲取方法參數(shù)類型
final Class<?>[] paramTypes = method.getParameterTypes();
//獲取方法參數(shù)上的注解
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
final SortedMap<Integer, String> map = new TreeMap<>();
int paramCount = paramAnnotations.length;
// get names from @Param annotations
for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
//從@Param注解上獲取value屬性值衍锚,并給name字段賦值
String name = null;
for (Annotation annotation : paramAnnotations[paramIndex]) {
if (annotation instanceof Param) {
hasParamAnnotation = true;
name = ((Param) annotation).value();
break;
}
}
if (name == null) {
// @Param was not specified.
//如果沒(méi)參數(shù)沒(méi)使用@Param注解
if (config.isUseActualParamName()) {
//從method中取出參數(shù)名稱友题,一般為arg0,arg1 ...
name = getActualParamName(method, paramIndex);
}
if (name == null) {
// use the parameter index as the name ("0", "1", ...)
// gcode issue #71
//如果前面幾個(gè)操作給name賦值都失敗了,最后使用下標(biāo)作為鍵值對(duì)的value
name = String.valueOf(map.size());
}
}
//key為參數(shù)下標(biāo)戴质,value為@Param注解value值或者mybatis指定默認(rèn)值
map.put(paramIndex, name);
}
names = Collections.unmodifiableSortedMap(map);
}
names鍵值對(duì)總結(jié)
從上述構(gòu)造方法可以看出度宦,names中的鍵值對(duì)應(yīng)該是{"0","paramValue"}或者{"1":"arg1"}這樣。
getNamedParams方法返回的map中的鍵值對(duì)應(yīng)該是{"paramValue":"0"}或者{"param1":"1"}這樣告匠。
其中:paramValue是指@Param注解的value屬性戈抄。param1是mybatis通用的參數(shù)key。
getNamedParams返回的數(shù)據(jù)類型有以下幾種:
- null:mapper方法中沒(méi)定義參數(shù)或者入?yún)閚ull后专。
- 除了map划鸽、null以外的其他Object類型,包括基本數(shù)據(jù)類型和java 對(duì)象:當(dāng)入?yún)⒅袃H有一個(gè)參數(shù)戚哎,而且沒(méi)有使用@Param注解時(shí)裸诽。
- map:使用了@Param注解或者mapper方法入?yún)⒉恢挂粋€(gè)。
SELECT方法中的參數(shù)繼續(xù)處理
SELECT類型的方法最后都在SqlSession的slectList方法中進(jìn)行統(tǒng)一處理型凳。
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
//先根據(jù)statement從configuration中獲取MappedStatement
//這里的statement就是mapper接口名.方法名
//String statementId = mapperInterface.getName() + "." + methodName;
MappedStatement ms = configuration.getMappedStatement(statement);
//這里的wrapCollection對(duì)方法又進(jìn)行了一層包裝
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
這里有必要說(shuō)明一下方法的入?yún)ⅲ?/p>
- statement:就是statementId:mapper接口名.方法名丈冬。詳見(jiàn)org.apache.ibatis.binding.MapperMethod.SqlCommand#resolveMappedStatement
- parameter:就是前面getNamedParams方法返回的數(shù)據(jù),可能是null啰脚,map以及其他object類型的數(shù)據(jù)殷蛇。
- rowBounds:分頁(yè)相關(guān)的數(shù)據(jù),這里是默認(rèn)的rowBounds橄浓,不分頁(yè)。
private Object wrapCollection(final Object object) {
//在對(duì)selectList方法入?yún)⑦M(jìn)行包裝前亮航,先判斷參數(shù)類型
if (object instanceof Collection) {
//這里判斷了是不是collection類型荸实,如果是則在外面使用map包一層,key為collection缴淋,value為入?yún)⒅底几_@里僅當(dāng)getNamedParams返回的是Object類型時(shí)才可能進(jìn)入泄朴,就是說(shuō)mapper方法的入?yún)⒅挥幸粋€(gè),而且沒(méi)有使用@Param注解
StrictMap<Object> map = new StrictMap<>();
map.put("collection", object);
if (object instanceof List) {
//這里再次判斷是否是List子類型露氮,如果是的話祖灰,再添加一個(gè)key為"list"的鍵值對(duì),方便動(dòng)態(tài)SQL中的<foreach>等使用
map.put("list", object);
}
return map;
} else if (object != null && object.getClass().isArray()) {
//如果是數(shù)組的話畔规,也會(huì)用map包裝一層局扶,key為"array"
StrictMap<Object> map = new StrictMap<>();
map.put("array", object);
return map;
}
return object;
}
總的來(lái)說(shuō),wrapCollection方法就是對(duì)getNamedParams處理后的參數(shù)再次進(jìn)行處理叁扫,如果是數(shù)組或者Collection對(duì)象三妈,則在外面用map包裝一層,方便后續(xù)的動(dòng)態(tài)SQL使用參數(shù)莫绣。
緊接著就到了SimpleExecutor的doQuery方法了
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
//這里的StatementHandler默認(rèn)是RoutingStatementHandler畴蒲,被代理類是PreparedStatementHandler
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
//調(diào)用內(nèi)部私有方法
stmt = prepareStatement(handler, ms.getStatementLog());
//查詢
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
//底層數(shù)據(jù)庫(kù)服務(wù)獲取數(shù)據(jù)庫(kù)連接connection
Connection connection = getConnection(statementLog);
//調(diào)用底層connection的prepareStatement方法預(yù)編譯SQL
stmt = handler.prepare(connection, transaction.getTimeout());
//handler 參數(shù)化
handler.parameterize(stmt);
return stmt;
}
DefaultParameterHandler.setParameters()方法
public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
//遍歷 ParameterMapping,ParameterMapping中包含屬性对室,javaType模燥、jdbcType等
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
//SQL中參數(shù)名,#{參數(shù)名}
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) {
//動(dòng)態(tài)SQL時(shí)掩宜,解析時(shí)會(huì)自動(dòng)假如其他的參數(shù)值
// issue #448 ask first for additional params
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
//如果mapper方法的入?yún)arameterObject為空涧窒,則直接返回null
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
//如果parameterObject是簡(jiǎn)單基本類型的話,則value直接等于parameterObject
value = parameterObject;
} else {
//如果parameterObject是map或者java bean等復(fù)雜類型的話锭亏,構(gòu)造MetaObject纠吴,方便通過(guò)屬性或者多層嵌套(如user.name)取值
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) {
jdbcType = configuration.getJdbcTypeForNull();
}
try {
//通過(guò)typehandler set參數(shù)值到SQL中
typeHandler.setParameter(ps, i + 1, value, jdbcType);
} catch (TypeException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
} catch (SQLException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
}
}
}
}
}
緊接著就是PreparedStatementHandler的query方法。
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
PreparedStatement ps = (PreparedStatement) statement;
//這里直接調(diào)用execute方法慧瘤,最后通過(guò)數(shù)據(jù)庫(kù)底層驅(qū)動(dòng)(如mysql)的PreparedStatement實(shí)現(xiàn)類完成execute方法戴已。執(zhí)行SQL
ps.execute();
return resultSetHandler.handleResultSets(ps);
}