您的位置:首页 > 移动开发

[Mybatis] Mapper接口原理分析

2016-12-29 12:39 429 查看
上篇文章中,是直接用SqlSession.selectList()去执行一条SQL的,但是作为 一个ORM框架,我们往往是调用接口去执行,如下所示:

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);

SqlSession sqlSession = factory.openSession();
UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
userMapper.selectAllUser();//直接调用接口执行

sqlSession.close();


但是UserMapper只是一个接口,并没有相应的实现类。我们都知道接口要有实现类才能实例化进而调用,但是那么Myabtis是如何实现调用没有实现类的方法,还能完成相应的SQL处理逻辑。

其实原理很简单:这个是用了JDK的动态代理技术,首先为UserMapper生成一个代理对象,由代理对象去调用SqlSession方法。也就是说在调用链SqlSession作为参数一直传递下去,并交给代理对象,真正的执行操作还是由SqlSession去执行的。

下面我们来分析下这其中的过程,先看下sqlSession.getMapper()方法:

@Override
public <T> T getMapper(Class<T> type) {
//从配置中获取,注意这两个参数,一个是接口UserMapper.class,另一个是SqlSession自身,特别是SqlSession这个参数,后文一系列的调用链都有这个参数的
return configuration.<T>getMapper(type, this);
}


再看下configuration.getMapper()

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//其实是调用了MapperRegistry的方法
return mapperRegistry.getMapper(type, sqlSession);
}


MapperRegistry类:

public class MapperRegistry {

private final Configuration config;
//Map类型,<Class,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代理工厂
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);
}
}

}


继续往下看MapperProxyFactory,从名字中可以直接知道这个是:Mapper代理工厂。

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;
}

@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
//很明显,这就是一个动态代理,用于生产一个代理对象
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);//创建一个Mapper代理
return newInstance(mapperProxy);//实例化一个代理对象,也就是UserMapper的代理对象
}

}


到了此步,创建代理对象就完成了,后面的内容注释使用代理对象执行SQL操作了。

来看代理类MapperProxy:

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.mapperInterfa
4000
ce = mapperInterface;
this.methodCache = methodCache;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//注意这个判断,获取该方法的对应的类,如果是Object,也就是说该方法为toString(),equals()等根类Object的方法。则调用代理类MapperProxy自身。
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
//在代理对象中执行SQL
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;
}

}


最后看下MapperMethod类,也就是真正执行SQL的类

public class MapperMethod {

public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
//判断这条SQL是什么类型的CRUD,最终有SqlSession去执行!也就是说整个调用还是交了SqlSession处理了!
if (SqlCommandType.INSERT == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
} else if (SqlCommandType.UPDATE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
} else if (SqlCommandType.DELETE == command.getType()) {
Object param = method.convertArgsT oSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
} else if (SqlCommandType.SELECT == command.getType()) {
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 {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
} else if (SqlCommandType.FLUSH == command.getType()) {
result = sqlSession.flushStatements();
} else {
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;
}

}


框架流程总结如下:

MapperRegistry获取到MapperProxyFactory工厂

MapperProxyFactory工厂创建MapperProxy

MapperProxy调用SqlSession执行SQL操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis orm