前言
Mybatis參數處理是Mybatis核心內容,圍繞著Mybatis的面試題也是層出不窮。接下來跟隨源碼看下Mybatis是如何處理參數的。
代碼示例
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 {
//這里注入的實際上是一個代理類
@Autowired
private ApplicationMapper applicationMapper;
@Test
public void testMybatis(){
ApplicationEntity applicationEntity = applicationMapper.getByCode("w1111");
System.out.println(applicationEntity);
}
}
- 這里注入的實際上是一個代理類,這個代理類是在應用啟動的時候spring發現其他bean注入了這個類,就通過BeanFactory.getBean(),再通過FactoryBean(MapperFactoryBean).getObject(),最后通過動態代理注入得到。Mybatis參數處理
idea debug進入下一步,可以發現進入了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緩存起來
final MapperMethod mapperMethod = cachedMapperMethod(method);
//最后執行mapperMethos.execute()方法
return mapperMethod.execute(sqlSession, args);
}
private MapperMethod cachedMapperMethod(Method method) {
return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
接下來看下MapperMethod.execute()方法是如何處理參數的。
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;
}
可以看到對于參數處理,都是通過Object param = method.convertArgsToSqlCommandParam(args);去處理的,那么我們看下這個方法到底做了什么操作。
public Object convertArgsToSqlCommandParam(Object[] args) {
return paramNameResolver.getNamedParams(args);
}
public Object getNamedParams(Object[] args) {
final int paramCount = names.size();
if (args == null || paramCount == 0) {
//如果沒有入參,或者方法定義參數個數為0,直接返回null
return null;
} else if (!hasParamAnnotation && paramCount == 1) {
//如果沒有使用@Param注解,且參數個數為1個,直接返回入參
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的鍵值對放入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()方法的入參args就是mapper接口上方法值。
names是一個SortedMap,內部的鍵值對,key為參數在接口方法中的索引位置(方法入參中的第幾個參數,從0開始),value為@Param的value值(如果沒有使用@Param注解,默認為arg0,arg1...)。
這一部分可從ParamNameResolver的構造函數中看出。
public ParamNameResolver(Configuration config, Method method) {
//獲取方法參數類型
final Class<?>[] paramTypes = method.getParameterTypes();
//獲取方法參數上的注解
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.
//如果沒參數沒使用@Param注解
if (config.isUseActualParamName()) {
//從method中取出參數名稱,一般為arg0,arg1 ...
name = getActualParamName(method, paramIndex);
}
if (name == null) {
// use the parameter index as the name ("0", "1", ...)
// gcode issue #71
//如果前面幾個操作給name賦值都失敗了,最后使用下標作為鍵值對的value
name = String.valueOf(map.size());
}
}
//key為參數下標,value為@Param注解value值或者mybatis指定默認值
map.put(paramIndex, name);
}
names = Collections.unmodifiableSortedMap(map);
}
names鍵值對總結
從上述構造方法可以看出,names中的鍵值對應該是{"0","paramValue"}或者{"1":"arg1"}這樣。
getNamedParams方法返回的map中的鍵值對應該是{"paramValue":"0"}或者{"param1":"1"}這樣。
其中:paramValue是指@Param注解的value屬性。param1是mybatis通用的參數key。
getNamedParams返回的數據類型有以下幾種:
- null:mapper方法中沒定義參數或者入參為null。
- 除了map、null以外的其他Object類型,包括基本數據類型和java 對象:當入參中僅有一個參數,而且沒有使用@Param注解時。
- map:使用了@Param注解或者mapper方法入參不止一個。
SELECT方法中的參數繼續處理
SELECT類型的方法最后都在SqlSession的slectList方法中進行統一處理。
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
//先根據statement從configuration中獲取MappedStatement
//這里的statement就是mapper接口名.方法名
//String statementId = mapperInterface.getName() + "." + methodName;
MappedStatement ms = configuration.getMappedStatement(statement);
//這里的wrapCollection對方法又進行了一層包裝
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();
}
}
這里有必要說明一下方法的入參:
- statement:就是statementId:mapper接口名.方法名。詳見org.apache.ibatis.binding.MapperMethod.SqlCommand#resolveMappedStatement
- parameter:就是前面getNamedParams方法返回的數據,可能是null,map以及其他object類型的數據。
- rowBounds:分頁相關的數據,這里是默認的rowBounds,不分頁。
private Object wrapCollection(final Object object) {
//在對selectList方法入參進行包裝前,先判斷參數類型
if (object instanceof Collection) {
//這里判斷了是不是collection類型,如果是則在外面使用map包一層,key為collection,value為入參值。這里僅當getNamedParams返回的是Object類型時才可能進入,就是說mapper方法的入參只有一個,而且沒有使用@Param注解
StrictMap<Object> map = new StrictMap<>();
map.put("collection", object);
if (object instanceof List) {
//這里再次判斷是否是List子類型,如果是的話,再添加一個key為"list"的鍵值對,方便動態SQL中的<foreach>等使用
map.put("list", object);
}
return map;
} else if (object != null && object.getClass().isArray()) {
//如果是數組的話,也會用map包裝一層,key為"array"
StrictMap<Object> map = new StrictMap<>();
map.put("array", object);
return map;
}
return object;
}
總的來說,wrapCollection方法就是對getNamedParams處理后的參數再次進行處理,如果是數組或者Collection對象,則在外面用map包裝一層,方便后續的動態SQL使用參數。
緊接著就到了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默認是RoutingStatementHandler,被代理類是PreparedStatementHandler
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
//調用內部私有方法
stmt = prepareStatement(handler, ms.getStatementLog());
//查詢
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
//底層數據庫服務獲取數據庫連接connection
Connection connection = getConnection(statementLog);
//調用底層connection的prepareStatement方法預編譯SQL
stmt = handler.prepare(connection, transaction.getTimeout());
//handler 參數化
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中參數名,#{參數名}
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) {
//動態SQL時,解析時會自動假如其他的參數值
// issue #448 ask first for additional params
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
//如果mapper方法的入參parameterObject為空,則直接返回null
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
//如果parameterObject是簡單基本類型的話,則value直接等于parameterObject
value = parameterObject;
} else {
//如果parameterObject是map或者java bean等復雜類型的話,構造MetaObject,方便通過屬性或者多層嵌套(如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 {
//通過typehandler set參數值到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;
//這里直接調用execute方法,最后通過數據庫底層驅動(如mysql)的PreparedStatement實現類完成execute方法。執行SQL
ps.execute();
return resultSetHandler.handleResultSets(ps);
}