我們以往使用ibatis或者mybatis 都是以這種方式調用XML當中定義的CRUD標籤來執行SQL 比如這樣
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} </select> </mapper>
SqlSession session = sqlSessionFactory.openSession();
try {
Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
} finally {
session.close();
}
這種方式有很明顯的缺點就是通過字符串去調用標籤定義的SQL,第一容易出錯,第二是當XML當中的id修改過以後你不知道在程序當中有多少個地方使用了這個ID,需要手工查找並一一修改。在Mybatis這個版本中做了一些改進,支持這種方式調用。
定義一個接口 方法名,參數需要與XML定義保持一致。
org.mybatis.example.BlogMapper.selectBlog
public interface BlogMapper {
Blog selectBlog(int id);
}
然後這麼調用,這樣以來當我們修改了XML的ID以後,只需要修改接口中的方法就可以了,編譯器會在其他使用該接口的地方報錯,很容易進行修改。當然好處還不只這些,還可以通過與Spring進行無縫集成,動態注入 等等。後面會一一講到。
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
} finally {
session.close();
}
本文的重點不是去講解如何使用MyBatis(關於如何使用Mybatis可以參考官方API http://mybatis.github.io/mybatis-3/zh/getting-started.html),而是講解MyBatis是如何通過接口對SqlSession進行動態封裝的。
在上面的例子當中呢,BlogMapper是一個接口 它並沒有實現類,爲什麼接口可以直接使用呢?
那是因爲MyBbatis使用了JDK動態代理機制動態生成了代理類,那麼代理類又是如何多SqlSession進行封裝的呢?
帶着這些疑問,讓我們通過分析源代碼的方式來解釋這些問題。
Mybatis關於包裝Mapper的代碼都在org.apache.ibatis.binding 這個包下面。
其中有4個類。
上面的4個類封裝了Mapper接口動態生成代理類的全部細節
MapperRegistry 類是註冊Mapper接口與獲取代理類實例的工具類
package org.apache.ibatis.binding;
import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
//這個類通過名字就可以看出 是用來註冊Mapper接口與獲取生成代理類實例的工具類
public class MapperRegistry {
//全局配置文件對象
private Configuration config;
//一個HashMap Key是mapper的類型對象, Value是MapperProxyFactory對象
//這個MapperProxyFactory是創建Mapper代理對象的工廠 我們一會在分析
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
public MapperRegistry(Configuration config) {
this.config = config;
}
//獲取生成的代理對象
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//通過Mapper的接口類型 去Map當中查找 如果爲空就拋異常
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null)
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
try {
//否則創建一個當前接口的代理對象 並且傳入sqlSession
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
public <T> boolean hasMapper(Class<T> type) {
return knownMappers.containsKey(type);
}
//註冊Mapper接口
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
knownMappers.put(type, new MapperProxyFactory<T>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
public Collection<Class<?>> getMappers() {
return Collections.unmodifiableCollection(knownMappers.keySet());
}
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
for (Class<?> mapperClass : mapperSet) {
addMapper(mapperClass);
}
}
//通過包名掃描下面所有接口
public void addMappers(String packageName) {
addMappers(packageName, Object.class);
}
}
MapperRegistry
package org.apache.ibatis.binding;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.ibatis.session.SqlSession;
//這個類負責創建具體Mapper接口代理對象的工廠類
public class MapperProxyFactory<T> {
//具體Mapper接口的Class對象
private final Class<T> mapperInterface;
//該接口下面方法的緩存 key是方法對象 value是對接口中方法對象的封裝
private Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
//構造參數沒啥好說的
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
//創建了一個代理類並返回
//關於Proxy的API 可以查看java官方的API
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
//在這裏傳入sqlSession 創建一個Mapper接口的代理類
public T newInstance(SqlSession sqlSession) {
//在這裏創建了MapperProxy對象 這個類實現了JDK的動態代理接口 InvocationHandler
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
//調用上面的方法 返回一個接口的代理類
return newInstance(mapperProxy);
}
}
MapperProxyFactory
package org.apache.ibatis.binding;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
//實現了JDK動態代理的接口 InvocationHandler
//在invoke方法中實現了代理方法調用的細節
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
//SqlSession
private final SqlSession sqlSession;
//接口的類型對象
private final Class<T> mapperInterface;
//接口中方法的緩存 有MapperProxyFactory傳遞過來的。
private final Map<Method, MapperMethod> methodCache;
//構造參數
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
//接口代理對象所有的方法調用 都會調用該方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//判斷是不是基礎方法 比如toString() hashCode()等,這些方法直接調用不需要處理
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
}
//這裏進行緩存
final MapperMethod mapperMethod = cachedMapperMethod(method);
//調用mapperMethod.execute 核心的地方就在這個方法裏,這個方法對纔是真正對SqlSession進行的包裝調用
return mapperMethod.execute(sqlSession, args);
}
//緩存處理
private MapperMethod cachedMapperMethod(Method method) {
MapperMethod mapperMethod = methodCache.get(method);
if (mapperMethod == null) {
mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
methodCache.put(method, mapperMethod);
}
return mapperMethod;
}
}
MapperProxy
package org.apache.ibatis.binding;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.*;
//這個類是整個代理機制的核心類,對Sqlsession當中的操作進行了封裝
public class MapperMethod {
//一個內部封 封裝了SQL標籤的類型 insert update delete select
private final SqlCommand command;
//一個內部類 封裝了方法的參數信息 返回類型信息等
private final MethodSignature method;
//構造參數
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, method);
}
//這個方法是對SqlSession的包裝調用
public Object execute(SqlSession sqlSession, Object[] args) {
//定義返回結果
Object result;
//如果是INSERT操作
if (SqlCommandType.INSERT == command.getType()) {
//處理參數
Object param = method.convertArgsToSqlCommandParam(args);
//調用sqlSession的insert方法
result = rowCountResult(sqlSession.insert(command.getName(), param));
//如果是UPDATE操作 同上
} else if (SqlCommandType.UPDATE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
//如果是DELETE操作 同上
} else if (SqlCommandType.DELETE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
//如果是SELECT操作 那麼情況會多一些 但是也都和sqlSession的查詢方法一一對應
} else if (SqlCommandType.SELECT == command.getType()) {
//如果返回void 並且參數有resultHandler
//則調用 void select(String statement, Object parameter, ResultHandler handler);方法
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
//如果返回多行結果這調用 <E> List<E> selectList(String statement, Object parameter);
//executeForMany這個方法調用的
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
//如果返回類型是MAP 則調用executeForMap方法
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else {
//否則就是查詢單個對象
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
} else {
//如果全都不匹配 說明mapper中定義的方法不對
throw new BindingException("Unknown execution method for: " + command.getName());
}
//如果返回值爲空 並且方法返回值類型是基礎類型 並且不是VOID 則拋出異常
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
private Object rowCountResult(int rowCount) {
final Object result;
if (method.returnsVoid()) {
result = null;
} else if (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType())) {
result = rowCount;
} else if (Long.class.equals(method.getReturnType()) || Long.TYPE.equals(method.getReturnType())) {
result = (long) rowCount;
} else if (Boolean.class.equals(method.getReturnType()) || Boolean.TYPE.equals(method.getReturnType())) {
result = (rowCount > 0);
} else {
throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: " + method.getReturnType());
}
return result;
}
private void executeWithResultHandler(SqlSession sqlSession, Object[] args) {
MappedStatement ms = sqlSession.getConfiguration().getMappedStatement(command.getName());
if (void.class.equals(ms.getResultMaps().get(0).getType())) {
throw new BindingException("method " + command.getName()
+ " needs either a @ResultMap annotation, a @ResultType annotation,"
+ " or a resultType attribute in XML so a ResultHandler can be used as a parameter.");
}
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
sqlSession.select(command.getName(), param, rowBounds, method.extractResultHandler(args));
} else {
sqlSession.select(command.getName(), param, method.extractResultHandler(args));
}
}
//返回多行結果 調用sqlSession.selectList方法
private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
List<E> result;
Object param = method.convertArgsToSqlCommandParam(args);
//如果參數含有rowBounds則調用分頁的查詢
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
} else {
//沒有分頁則調用普通查詢
result = sqlSession.<E>selectList(command.getName(), param);
}
// issue #510 Collections & arrays support
if (!method.getReturnType().isAssignableFrom(result.getClass())) {
if (method.getReturnType().isArray()) {
return convertToArray(result);
} else {
return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
}
}
return result;
}
private <E> Object convertToDeclaredCollection(Configuration config, List<E> list) {
Object collection = config.getObjectFactory().create(method.getReturnType());
MetaObject metaObject = config.newMetaObject(collection);
metaObject.addAll(list);
return collection;
}
@SuppressWarnings("unchecked")
private <E> E[] convertToArray(List<E> list) {
E[] array = (E[]) Array.newInstance(method.getReturnType().getComponentType(), list.size());
array = list.toArray(array);
return array;
}
private <K, V> Map<K, V> executeForMap(SqlSession sqlSession, Object[] args) {
Map<K, V> result;
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.<K, V>selectMap(command.getName(), param, method.getMapKey(), rowBounds);
} else {
result = sqlSession.<K, V>selectMap(command.getName(), param, method.getMapKey());
}
return result;
}
public static class ParamMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = -2212268410512043556L;
@Override
public V get(Object key) {
if (!super.containsKey(key)) {
throw new BindingException("Parameter '" + key + "' not found. Available parameters are " + keySet());
}
return super.get(key);
}
}
//一個內部類 封裝了具體執行的動作
public static class SqlCommand {
//xml標籤的id
private final String name;
//insert update delete select的具體類型
private final SqlCommandType type;
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) throws BindingException {
//拿到全名 比如 org.mybatis.example.BlogMapper.selectBlog
String statementName = mapperInterface.getName() + "." + method.getName();
MappedStatement ms = null;
//獲取MappedStatement對象 這個對象封裝了XML當中一個標籤的所有信息 比如下面
//<select id="selectBlog" resultType="Blog">
//select * from Blog where id = #{id}
//</select>
if (configuration.hasStatement(statementName)) {
ms = configuration.getMappedStatement(statementName);
} else if (!mapperInterface.equals(method.getDeclaringClass().getName())) { // 這裏是一個BUG
String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName();
if (configuration.hasStatement(parentStatementName)) {
ms = configuration.getMappedStatement(parentStatementName);
}
}
//爲空拋出異常
if (ms == null) {
throw new BindingException("Invalid bound statement (not found): " + statementName);
}
name = ms.getId();
type = ms.getSqlCommandType();
//判斷SQL標籤類型 未知就拋異常
if (type == SqlCommandType.UNKNOWN) {
throw new BindingException("Unknown execution method for: " + name);
}
}
public String getName() {
return name;
}
public SqlCommandType getType() {
return type;
}
}
//內部類 封裝了接口當中方法的 參數類型 返回值類型 等信息
public static class MethodSignature {
//是否返回多調結果
private final boolean returnsMany;
//返回值是否是MAP
private final boolean returnsMap;
//返回值是否是VOID
private final boolean returnsVoid;
//返回值類型
private final Class<?> returnType;
//mapKey
private final String mapKey;
//resultHandler類型參數的位置
private final Integer resultHandlerIndex;
//rowBound類型參數的位置
private final Integer rowBoundsIndex;
//用來存放參數信息
private final SortedMap<Integer, String> params;
//是否存在命名參數
private final boolean hasNamedParameters;
//在這裏對上面的屬性進行初始化 就不一一詳細說明了 具體實現細節可以看下面的代碼。
public MethodSignature(Configuration configuration, Method method) throws BindingException {
this.returnType = method.getReturnType();
this.returnsVoid = void.class.equals(this.returnType);
this.returnsMany = (configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray());
this.mapKey = getMapKey(method);
this.returnsMap = (this.mapKey != null);
this.hasNamedParameters = hasNamedParams(method);
this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
this.params = Collections.unmodifiableSortedMap(getParams(method, this.hasNamedParameters));
}
public Object convertArgsToSqlCommandParam(Object[] args) {
final int paramCount = params.size();
if (args == null || paramCount == 0) {
return null;
} else if (!hasNamedParameters && paramCount == 1) {
return args[params.keySet().iterator().next()];
} else {
final Map<String, Object> param = new ParamMap<Object>();
int i = 0;
for (Map.Entry<Integer, String> entry : params.entrySet()) {
param.put(entry.getValue(), args[entry.getKey()]);
// issue #71, add param names as param1, param2...but ensure backward compatibility
final String genericParamName = "param" + String.valueOf(i + 1);
if (!param.containsKey(genericParamName)) {
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}
public boolean hasRowBounds() {
return (rowBoundsIndex != null);
}
public RowBounds extractRowBounds(Object[] args) {
return (hasRowBounds() ? (RowBounds) args[rowBoundsIndex] : null);
}
public boolean hasResultHandler() {
return (resultHandlerIndex != null);
}
public ResultHandler extractResultHandler(Object[] args) {
return (hasResultHandler() ? (ResultHandler) args[resultHandlerIndex] : null);
}
public String getMapKey() {
return mapKey;
}
public Class<?> getReturnType() {
return returnType;
}
public boolean returnsMany() {
return returnsMany;
}
public boolean returnsMap() {
return returnsMap;
}
public boolean returnsVoid() {
return returnsVoid;
}
private Integer getUniqueParamIndex(Method method, Class<?> paramType) {
Integer index = null;
final Class<?>[] argTypes = method.getParameterTypes();
for (int i = 0; i < argTypes.length; i++) {
if (paramType.isAssignableFrom(argTypes[i])) {
if (index == null) {
index = i;
} else {
throw new BindingException(method.getName() + " cannot have multiple " + paramType.getSimpleName() + " parameters");
}
}
}
return index;
}
private String getMapKey(Method method) {
String mapKey = null;
if (Map.class.isAssignableFrom(method.getReturnType())) {
final MapKey mapKeyAnnotation = method.getAnnotation(MapKey.class);
if (mapKeyAnnotation != null) {
mapKey = mapKeyAnnotation.value();
}
}
return mapKey;
}
private SortedMap<Integer, String> getParams(Method method, boolean hasNamedParameters) {
final SortedMap<Integer, String> params = new TreeMap<Integer, String>();
final Class<?>[] argTypes = method.getParameterTypes();
for (int i = 0; i < argTypes.length; i++) {
if (!RowBounds.class.isAssignableFrom(argTypes[i]) && !ResultHandler.class.isAssignableFrom(argTypes[i])) {
String paramName = String.valueOf(params.size());
if (hasNamedParameters) {
paramName = getParamNameFromAnnotation(method, i, paramName);
}
params.put(i, paramName);
}
}
return params;
}
private String getParamNameFromAnnotation(Method method, int i, String paramName) {
final Object[] paramAnnos = method.getParameterAnnotations()[i];
for (Object paramAnno : paramAnnos) {
if (paramAnno instanceof Param) {
paramName = ((Param) paramAnno).value();
}
}
return paramName;
}
private boolean hasNamedParams(Method method) {
boolean hasNamedParams = false;
final Object[][] paramAnnos = method.getParameterAnnotations();
for (Object[] paramAnno : paramAnnos) {
for (Object aParamAnno : paramAnno) {
if (aParamAnno instanceof Param) {
hasNamedParams = true;
break;
}
}
}
return hasNamedParams;
}
}
}
MapperMethod
通過上面的分析就很容易弄清楚Mybatis是如何利用JDK動態代理的機制生成代理類來對各種Mapper接口進行封裝的了。