-
Binding模块主要内容是关于Mapper代理接口的生成和管理,组件关系图:
- 有关这部门的内容需要动态代理方面的知识,请不懂的补充相关动态代理的内容。
一、MapperRegistry
- MapperRegistry是Mapper接口及其对应的代理对象工厂的注册中心,源码:
public class MapperRegistry {
//mybatis全局唯一的配置对象,包含所有信息
private final Configuration config;
//mapper接口与MapperProxyFactory代理工厂之间的关系
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
//mybatis初始化过程中会调用这个方法填充knownMappers集合
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));
//注解和xml相关解析
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
//执行sql语句的时候会调用这个方法获取实现了zMapper接口的代理对象
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
//创建实现了type接口的代理对象
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
二、MapperProxyFactory
- 主要负责创建代理对象,源码:
public class MapperProxyFactory<T> {
//mapper接口对象
private final Class<T> mapperInterface;
//mapperInterface中某一个方法对应的Method对象,值是MapperValue对象
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public T newInstance(SqlSession sqlSession) {
//创建mapperProxy对象,每一次调用都会创建新的mapperProxy对象
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
//创建实现了mapperInterface接口的代理对象
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
...
三、MapperProxy
- 实现了InvocationHandler接口,是代理对象的核心逻辑
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;//mapper接口对应的class对象
private final Map<Method, MapperMethod> methodCache;//用于缓存MapperMethod、可以在多个代理对象之间共享
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 {
try {
//如果继承Objecy直接调用
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
//从缓存中获取MapperMethod对象,有就获取没有就存入
final MapperMethod mapperMethod = cachedMapperMethod(method);
//MapperMethod中执行sql语句
return mapperMethod.execute(sqlSession, args);
}
四、MapperMethod
- 封装了Mapper接口与中对应的信息,以及对应sql语句的信息。也就是说MapperMethod是连接Mapper接口欧以及配置文件中定义的sql语句的桥梁
public class MapperMethod {
//记录sql语句的名称和类型
private final SqlCommand command;
//mapper接口中对应方法相关信息
private final MethodSignature method;
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
//根据sql类型调用sqlSession对应的方法
switch (command.getType()) {
case INSERT: {
//负责将args[]实际参数数组转为sql语句对应的参数列表
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);
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
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;
}
1、SqlCommand
- MapperMethod的内部类,使用name字段记录sql语句的名称,type字段记录sql语句的类型
public static class SqlCommand {
private final String name;
//SqlCommandType是枚举类型包含crud等
private final SqlCommandType type;
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
final String methodName = method.getName();
final Class<?> declaringClass = method.getDeclaringClass();
//解析获取MappedStatement
MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
configuration);
if (ms == null) {
//@flushz注解
if (method.getAnnotation(Flush.class) != null) {
name = null;
type = SqlCommandType.FLUSH;
} else {
throw new BindingException("Invalid bound statement (not found): "
+ mapperInterface.getName() + "." + methodName);
}
} else {
//获取到name和type
name = ms.getId();
type = ms.getSqlCommandType();
if (type == SqlCommandType.UNKNOWN) {
throw new BindingException("Unknown execution method for: " + name);
}
}
}
private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
Class<?> declaringClass, Configuration configuration) {
//mapper接口的名称+对应方法(config配置文件中各个组件的id)
String statementId = mapperInterface.getName() + "." + methodName;
if (configuration.hasStatement(statementId)) {
//MappedStatement封装了sql语句的相关信息,在初始化时候创建
return configuration.getMappedStatement(statementId);
//如果父类类型和接口一样说明不是接口
} else if (mapperInterface.equals(declaringClass)) {
return null;
}
//向上遍历接口
for (Class<?> superInterface : mapperInterface.getInterfaces()) {
if (declaringClass.isAssignableFrom(superInterface)) {
//递归
MappedStatement ms = resolveMappedStatement(superInterface, methodName,
declaringClass, configuration);
if (ms != null) {
return ms;
}
}
}
return null;
}
}
2、MethodSignature
- 也是其内部类,封装了Mapper接口中定义的方法的相关信息
private final boolean returnsMany;//返回值是否是collection类型或者数组
private final boolean returnsMap;//返回值是否是Map类型
private final boolean returnsVoid;//返回值是否是void
private final boolean returnsCursor;//返回值是否是cursor类型
private final Class<?> returnType;//返回值类型
private final String mapKey;//返回为map则该字段记录作为key的列名
private final Integer resultHandlerIndex;//标记ResultHandler类性参数的位置
private final Integer rowBoundsIndex;//rowBounds类型的位置
//ParamNameResolver对象
private final ParamNameResolver paramNameResolver;
//解析相应的method,初始化上述的字段
public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);
if (resolvedReturnType instanceof Class<?>) {
this.returnType = (Class<?>) resolvedReturnType;
} else if (resolvedReturnType instanceof ParameterizedType) {
this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();
} else {
this.returnType = method.getReturnType();
}
this.returnsVoid = void.class.equals(this.returnType);
this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();
this.returnsCursor = Cursor.class.equals(this.returnType);
this.mapKey = getMapKey(method);
this.returnsMap = this.mapKey != null;
this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
this.paramNameResolver = new ParamNameResolver(configuration, method);
}
3、ParamNameResolver
- 处理mapper接口中定义的方法的参数列表
public class ParamNameResolver {
//可以使用@param注解进行参数设置
private static final String GENERIC_NAME_PREFIX = "param";
//记录参数在参数列表中的位置索引与参数名称之间的关系
private final SortedMap<Integer, String> names;
//判断是否使用了注解@param
private boolean hasParamAnnotation;
public ParamNameResolver(Configuration config, Method method) {
//获取参数类型数组
final Class<?>[] paramTypes = method.getParameterTypes();
//参数列表上的注解
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
//用于记录参数索引与参数名称之间的关系
final SortedMap<Integer, String> map = new TreeMap<Integer, String>();
int paramCount = paramAnnotations.length;
// get names from @Param annotations
for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
if (isSpecialParameter(paramTypes[paramIndex])) {
// skip special parameters
continue;
}
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.根据配置决定是否采用实际名称作为其名称
if (config.isUseActualParamName()) {
name = getActualParamName(method, paramIndex);
}
if (name == null) {
// use the parameter index as the name ("0", "1", ...)
name = String.valueOf(map.size());
}
}
map.put(paramIndex, name);
}
names = Collections.unmodifiableSortedMap(map);
}
//传入实际参数与之关联
public Object getNamedParams(Object[] args) {
final int paramCount = names.size();
if (args == null || paramCount == 0) {
return null;
//没有使用注解@param且只有一个参数
} else if (!hasParamAnnotation && paramCount == 1) {
return args[names.firstKey()];
} else {
final Map<String, Object> param = new ParamMap<Object>();
int i = 0;
for (Map.Entry<Integer, String> entry : names.entrySet()) {
//将参数名和实际参数记录到param中
param.put(entry.getValue(), args[entry.getKey()]);
// 创建索引默认值例如 (param1, param2, ...)
final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
// 如果@param注解指定的参数名称就是param+索引格式的就不需要再添加了
if (!names.containsValue(genericParamName)) {
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}
4、MapperMethod中其他方法
1)执行完毕update、insert、delete语句时候执行结果处理
//将sql插入等方法返回的int转为mapper中方法需要的返回类型
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;
}
(2)select时候使用resultHandler处理
private void executeWithResultHandler(SqlSession sqlSession, Object[] args) {
MappedStatement ms = sqlSession.getConfiguration().getMappedStatement(command.getName());
if (!StatementType.CALLABLE.equals(ms.getStatementType())
&& 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));
}
}
(3)返回集合类型
private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
List<E> result;
Object param = method.convertArgsToSqlCommandParam(args);
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;
}
四、总结
- mybatis中使用Binding模块对Mapper代理接口的产生进行包装。MapperRegistry用于Mapper接口的注册和代理Mapper接口的产生,然后由MapperProxyFactory创建代理对象MapperProxy,MapperProxy实现了InvocationHandler接口,是代理对象的核心逻辑,当客户端调用代理对象的方法时候就会调用MapperProxy对象的invoke方法完成动态代理过程。
- 调用invoke方法后最终执行的是MapperMethod的execute方法,再此之前会创建MapperMethod实现两个内部类SqlCommand和MethodSignature的初始化。最后会根据配置执行相应的crud方法(具体的执行流程会在后面仔细讲解)