调用链
之前已经介绍到了如何创建DefaultSqlSession
,下一步就是通过会话创建对应的Mapper接口了,但是按照我们Java的知识,接口是没有办法直接创建的,那么Mybatis是如何处理这个的? 其实这里是采用了代理
// 我们自己编写的创建获取Mapper的代码
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
DefaultSqlSession 类获取Mapper
@Override
public <T> T getMapper(Class<T> type) {
// 通过配置文件获取Mapper
return configuration.<T>getMapper(type, this);
}
Configuration 类关于Mapper的方法,看到底层都是通过一个注册类 mapperRegistry 来存储/获取
// 注册Mapper
public void addMappers(String packageName, Class<?> superType) {
mapperRegistry.addMappers(packageName, superType);
}
public void addMappers(String packageName) {
mapperRegistry.addMappers(packageName);
}
public <T> void addMapper(Class<T> type) {
mapperRegistry.addMapper(type);
}
// 获取Mapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
// 包含Mapper
public boolean hasMapper(Class<?> type) {
return mapperRegistry.hasMapper(type);
}
MapperRegistry
MapperRegistry 顾名思义,就是用于注册Mapper接口的,在里面存在一个Map来存储,同时在Configuration存在一个该实例,保证全局唯一
注意这里的key是Class类型,value是MapperProxyFactory类型,注意这里是代理工厂
public class MapperRegistry {
// 全局配置
private final Configuration config;
// 注册的对象 存储到Map
// 注意这里的value类型是MapperProxyFactory
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
public MapperRegistry(Configuration config) {
this.config = config;
}
// 获取Mapper
@SuppressWarnings("unchecked")
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 {
// 通过Mapper代理工厂创建代理类,返回
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);
}
// 添加
public <T> void addMapper(Class<T> type) {
// Mapper类型必须是接口
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
// 是否加载完成标记
boolean loadCompleted = false;
try {
// 存储到Map里面
knownMappers.put(type, new MapperProxyFactory<T>(type));
// 映射器注解构建器
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
// 解析映射接口类,因为我们的mapper接口可以添加注解
// 该方法解析mapper标签下的所有方法和注解,并对解析出来的信息加以封装
parser.parse();
loadCompleted = true;
} finally {
// 如果完成加载 则移除这个映射类
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
// 获取已经注册映射接口集合
public Collection<Class<?>> getMappers() {
// 返回不可修改的集合
return Collections.unmodifiableCollection(knownMappers.keySet());
}
// 批量添加包下的Mapper
public void addMappers(String packageName, Class<?> superType) {
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);
}
}
MapperProxyFactory
在上面的 MapperRegistry
类的getMapper()
,是通过代理工厂来创建一个代理类返回
public class MapperProxyFactory<T> {
// 接口
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
// 构造方法
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
// getter方法
public Class<T> getMapperInterface() {
return mapperInterface;
}
// getter方法
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
// 通过代理类创建MapperProxy代理类
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
// 通过代理类返回指定接口的代理类实例
// 参数1:类加载器
// 参数2:接口
// 参数3:代理对象 该对象需要实现InvocationHandler接口
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
// 创建一个代理对象
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}
MapperProxyFactory 代理工厂在最底层会创建一个代理对象 MapperProxy 返回,所以表面上看着是一个接口,但是通过Debug可以看到,就是代理对象,那我们调用接口里面的方法,其实就是调用代理对象中的方法
// Proxy代理类
// 返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序
public static Object newProxyInstance(ClassLoader loader,
类<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
MapperProxy
MapperProxy为代理对象类,该类实现了InvocationHandler
接口,Mapper接口调用的方法都会被代理到invoke()
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
// 接口
private final Class<T> mapperInterface;
// 方法缓存
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;
}
/**
* 代理方法回调
* @param proxy 代理后的实例对象
* @param method 对象被调用方法
* @param args 调用时的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 如果声明的类型是Object类型
if (Object.class.equals(method.getDeclaringClass())) {
// 直接执行
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {// 判断是否是 default 方法
// 执行default方法
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
// 接口生成的方法转换成MapperMethod
final MapperMethod mapperMethod = cachedMapperMethod(method);
// 执行SQL 获取结果 处理后返回
return mapperMethod.execute(sqlSession, args);
}
// 获取MapperMethod 没有则创建一个 并且存入
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;
}
// 执行默认方法
@UsesJava7//该注解可以看到在JDK7的时候使用
private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
throws Throwable {
final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
.getDeclaredConstructor(Class.class, int.class);
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
final Class<?> declaringClass = method.getDeclaringClass();
return constructor
.newInstance(declaringClass,
MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
| MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
.unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
}
// 因为JDK1.8以后接口支持默认方法,也就是被default修饰的方法 此方法是判断
private boolean isDefaultMethod(Method method) {
return ((method.getModifiers()
& (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC)
&& method.getDeclaringClass().isInterface();
}
}
MapperMethod
上面的invoke()
,会把方法转移到MapperMethod
类,这个类就相当于是一个中间类,该类主要做几件事
- 处理参数,将java参数转换成sql参数,主要就是就是在里面另外添加 param0,param1,…
- 通过SQL的类型以及返回结果的类型,调用SqlSession里面对应的增/删/改/查 方法
- 处理返回结果,转换成对应的类型
public class MapperMethod {
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, mapperInterface, method);
}
// 执行方法
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
// 判断SQL类型 通过switch-case判断
// 1.转换参数 这个方法需要看一下,可以通过param0使用参数 就是因为这里
// 2.底层就是通过sqlSession调用方法,这就和之前的Mybatis四大组件连接上了
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()) {// 返回Map
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;
}
// 处理结果 返回修改的行数 或者 布尔值`
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;
}
// 用ResultHandler执行查询sql
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));
}
}
// 执行查询SQL,默认返回结果对象集合
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;
}
// 执行查询SQL,返回结果对象游标
private <T> Cursor<T> executeForCursor(SqlSession sqlSession, Object[] args) {
Cursor<T> result;
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.<T>selectCursor(command.getName(), param, rowBounds);
} else {
result = sqlSession.<T>selectCursor(command.getName(), param);
}
return result;
}
// 将结果转换成返回类型 ,method返回类型必须是Collection的子类
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> Object convertToArray(List<E> list) {
Class<?> arrayComponentType = method.getReturnType().getComponentType();
Object array = Array.newInstance(arrayComponentType, list.size());
if (arrayComponentType.isPrimitive()) {
for (int i = 0; i < list.size(); i++) {
Array.set(array, i, list.get(i));
}
return array;
} else {
return list.toArray((E[])array);
}
}
// 执行查询SQL,返回结果对象映射
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;
}
}
ParamMap 静态内部类
封装的HashMap,主要用于返回Mybatis特定的异常信息
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);
}
}
SqlCommand 静态内部类
单独封装了一套静态内部类,根据内容判断主要就是为了解决接口继承的问题,因为我们调用的接口可能是父类接口的方法,然后又进了MappedStatement的获取,这样在使用的时候更方便
// Sql公共属性
public static class SqlCommand {
// 类名+方法名 对应着唯一的方法
private final String name;
// DML标签的类型
private final SqlCommandType type;
// 构造方法
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
// 接口方法名
final String methodName = method.getName();
// 接口类
final Class<?> declaringClass = method.getDeclaringClass();
// 获取DML标签封装类
MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,configuration);
if (ms == null) {// 正常都会获取到
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为类名+方法名
name = ms.getId();
// SQL类型
type = ms.getSqlCommandType();
if (type == SqlCommandType.UNKNOWN) {
throw new BindingException("Unknown execution method for: " + name);
}
}
}
public String getName() {
return name;
}
public SqlCommandType getType() {
return type;
}
// 解析DML标签
private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
Class<?> declaringClass, Configuration configuration) {
//拼装statementId,取映射器接口包名+类名+'.'+方法名
String statementId = mapperInterface.getName() + "." + methodName;
if (configuration.hasStatement(statementId)) {
// 也是从configuration里面获取解析好的
return configuration.getMappedStatement(statementId);
} else if (mapperInterface.equals(declaringClass)) {
// 如果映射器接口类等于声明method的类
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;
}
}
MethodSignature 静态内部类
// 类名意思为方法特征
public static class MethodSignature {
private final boolean returnsMany;// 返回结果是集合类型
private final boolean returnsMap; // 返回结果是Map类型
private final boolean returnsVoid;// 无返回
private final boolean returnsCursor;// 返回游标
private final Class<?> returnType;// 返回类型
private final String mapKey; //
private final Integer resultHandlerIndex;
private final Integer rowBoundsIndex;
private final ParamNameResolver paramNameResolver;// 参数解析器
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);
}
// 将Java参数转换成sql脚本参数
// 假如方法传入了一个参数,那么这里一般会在这个基础上,增加一个param0 param1
// 也就是我们在mapper文件中使用一个参数 可以通过参数名,或者 ‘param0’ 就是在这里处理的
// 其实就是遍历添加到一个Map里面
public Object convertArgsToSqlCommandParam(Object[] args) {
return paramNameResolver.getNamedParams(args);
}
// 省略一些getter方法
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;
}
}
上面解析参数convertArgsToSqlCommandParam()
用到了getNamedParams()
private static final String GENERIC_NAME_PREFIX = "param";
public Object getNamedParams(Object[] args) {
final int paramCount = names.size();
if (args == null || paramCount == 0) {
return null;
} 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()) {
// 添加正常key-value
param.put(entry.getValue(), args[entry.getKey()]);
// add generic param names (param1, param2, ...)
final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
// ensure not to overwrite parameter named with @Param
if (!names.containsValue(genericParamName)) {
// 添加param1,param2,...
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}
aram = new ParamMap();
int i = 0;
for (Map.Entry<Integer, String> entry : names.entrySet()) {
// 添加正常key-value
param.put(entry.getValue(), args[entry.getKey()]);
// add generic param names (param1, param2, …)
final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
// ensure not to overwrite parameter named with @Param
if (!names.containsValue(genericParamName)) {
// 添加param1,param2,…
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}